问题描述
我刚开始使用 Java (SE 8)
这是我的代码:
public class Foo {
public static int sum(int[] arr) {
int ans = 0;
for (int i = 0; i < arr.length; i++) {
ans += arr[i];
}
return ans;
}
public static int[] takeInput() {
Scanner s = new Scanner(System.in);
int size = s.nextInt();
int arr[] = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = s.nextInt();
}
return arr;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int testCases = s.nextInt();
while (testCases-- > 0) {
int arr[] = takeInput();
System.out.println(sum(arr));
}
}
}
由于某种原因,我收到了 NoSuchElementException
java.util.NoSuchElementException
at line 937,java.base/java.util.Scanner.throwFor
at line 1594,java.base/java.util.Scanner.next
at line 2258,java.base/java.util.Scanner.nextInt
at line 2212,java.base/java.util.Scanner.nextInt
at line 18,Solution.takeInput
at line 32,Solution.main
基本上必须找到每个数组的元素之和
输入:
2
5
1 2 3 4 5
3
10 20 30
输出:
15 60
我在这里做错了什么?
解决方法
我认为您应该使用一个 Scanner 实例。
res
,
此处可能的答案:Scanner error with nextInt()
所以对于你的代码
public static void main (String[] args)
{
Scanner s = new Scanner (System.in);
if(s.hasNext()) {
int testCases = s.nextInt();
while (testCases-- > 0)
{
int arr[] = takeInput();
System.out.println (sum (arr));
}
}
s.close();
}
会有所帮助。