NoSuchElementException 的原因(Java SE 1.8)

Reason for NoSuchElementException (Java SE 1.8)

我刚开始使用 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 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();
    }

会有帮助。

我认为你应该使用 一个 Scanner 实例

public class MavenMain {

    private static int sum(int[] arr) {
        int sum = 0;

        for (int i = 0; i < arr.length; i++)
            sum += arr[i];

        return sum;
    }

    private static int[] takeInput(Scanner scan) {
        int[] arr = new int[scan.nextInt()];

        for (int i = 0; i < arr.length; i++)
            arr[i] = scan.nextInt();

        return arr;
    }

    public static void main(String... args) {
        Scanner scan = new Scanner(System.in);
        int testCases = scan.nextInt();

        while (testCases-- > 0) {
            int[] arr = takeInput(scan);
            System.out.println(sum(arr));
        }
    }

}