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 实例

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();
    }

会有所帮助。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...