2014-03-13 73 views
-1

我正在构建一个数组,询问您有多少个不同的输入,然后让您输入每个输入。最后我想总结一下,但我一直在收到错误。 同样,当我超过5个输入时,我输了一个.....例如,当我回答第一个问题时:输入“10”。当我开始添加不同的数字时,它停在九点。请帮忙。Java - 总结阵列列表值

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]; 
    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); 
+2

你找到总和的逻辑没有意义。 –

+1

你怎么能这样做'int totalSum = numArr + totalSum;' –

+1

'int totalSum = numArr + totalSum;' - 它应该做什么? 'totalSum'尚未定义。 2.你正在向int数组中加入int。这显然不起作用。 – sashkello

回答

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

这工作。谢谢! – user3413450

+0

不客气..不要忘记竖起大拇指! –

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); 
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是一个数组 - 你必须访问索引,而不是整个数组!