我一直在试图让这个程序工作,应该继续从用户输入,直到输入-1并计算总和。 问题如下: 设计并实现一个Java程序(命名为 InputSum ),它提示用户输入一个正整数 。该程序应为ac cept整数,直到用户输入值-1 (负数)。用户输入-1后,程序 应显示输入的数字,然后显示其总和 ,如下所示。请注意,-1不是输出的一部分。 确保程序 在proc 之前验证每个输入的号码,因为用户可以输入除句号值-1 以外的负数 数字。
设计你的程序,使其 允许用户重新运行 程序与上面显示的同一运行中的一组不同的输入。 记录您的代码,并按上图所示组织空间输出。想不通为什么程序将无法正常运行
这里是我的代码:
/* Class: CS1301
* Section: 9:30
* Term: Fall 2015
* Name: Matthew Woolridge
* Instructor: Mr. Robert Thorsen
* Assignment: Assignment 6
* Program: 1
* ProgramName: InputSum
* Purpose: The program prompts the user to input numbers until -1 is entered and calculates the sum
* Operation: The information is statically instantiated in the code and
* the data is output to the screen.
* Input(s): The input is the numbers
* Output(s): The output will be the sum of the numbers
* Methodology: The program will use loops to determine if numbers or still to be entered or if -1 was entered
*
*/
import java.util.*;
import java.io.*;
public class InputSum
{
public static void main (String[] args)
{
/******************************************************************************
* Declarations Section *
******************************************************************************/
/****************************CONSTANTS********************************/
Scanner scan = new Scanner(System.in); //Initializes scanner
int n = 1;
int [] num = new int[n]; //Creates array for input numbers
int i;
int sum=0;
/******************************************************************************
* Inputs Section *
******************************************************************************/
System.out.print("Please input integers, note that -1 ends the submissions: "); //Prompts the user for input
/****************************variables********************************/
//***************************Calculations in processing************************//
/******************************************************************************
* Processing Section *
******************************************************************************/
for(i=0; i<num.length; i++)
{
num[i] = scan.nextInt(); //Continues to read numbers and add them to the sum
n = n + 1; //Adds to the array maximum
sum = sum + num[i]; //Calculates the sum
if (num[i] == -1){
break;
}
}
System.out.print("The numbers entered are: " + num[i]);
System.out.print("\nThe sum of the numbers is: " + sum);
/******************************************************************************
* Outputs Section *
******************************************************************************/
//***************Output is in the processing**************************//
}
}
的问题是,该方案不断得到在哪里它应该打印之行挂断了电话。任何和所有的帮助表示赞赏!
你的程序是因为你的数组大小是'1',所以它只能接受'num [0]'的值。 –
由于您不知道用户使用阵列输入的值有多少,因此是不好的选择。使用一些根据需要扩展的数据结构。例如。一个ArrayList应该适合你的需求。 –
我应该如何去使用一个数组列表,我没有必要经常使用它,说实话。 – snipem1438