我正在构建一个数组,询问您有多少不同的输入,然后允许您输入每个输入。最后我想总结一下,但我一直都会收到错误。 当我超过5个输入时,我输了一个.....例如,当我回答第一个问题时:输入“10”。当我开始添加不同的数字时,它停在九点。请帮忙。
public static void main(String [] args){ 扫描仪输入=新扫描仪(System.in);
System.out.println("Please enter the number of courses you have left: ");
int size = input.nextInt();
int[] numArr = new int[size];
System.out.println("Enter the number of CUs for each course: ");
for (int i=0; i<numArr.length; i++)
{
numArr[i] = input.nextInt();
}
int totalSum = numArr + totalSum;
System.out.print("The sum of the numbers is: " + totalSum);
答案 0 :(得分:2)
将您的逻辑和代码更改为以下内容:
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of courses you have left: ");
int size = input.nextInt();
System.out.println("Enter the number of CUs for each course: ");
int totalSum = 0;
for (int i = 0; i < size; i++) {
totalSum+=input.nextInt();
}
System.out.print("The sum of the numbers is: " + totalSum);
答案 1 :(得分:1)
试
System.out.println("Please enter the number of courses you have left: ");
int size = input.nextInt();
int totalSum = 0;
for (int i=0; i< size; i++)
{
System.out.println("Enter the number of CUs for each course: ");
int cuNum = input.nextInt();
totalSum += cuNum ;
}
System.out.print("The sum of the numbers is: " + totalSum);
答案 2 :(得分:1)
非常确定您的预期结果是
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of courses you have left: ");
int size = input.nextInt();
int[] numArr = new int[size];
int totalSum = 0;
System.out.println("Enter the number of CUs for each course: ");
for (int i=0; i<numArr.length; i++)
{
numArr[i] = input.nextInt();
totalSum += numArr[i];
}
System.out.print("The sum of the numbers is: " + totalSum);
}
您的其他代码无效,主要是因为
int totalSum = numArr + totalSum;
您无法定义totalSum来定义自己!你不能只使用numArr ... numArr是一个数组 - 你必须访问索引,而不是整个数组!