【问题标题】:java.util.NoSuchElementExceptionjava.util.NoSuchElementException
【发布时间】:2018-02-11 16:46:46
【问题描述】:
Scanner  sc=new Scanner(System.in);
    int k=sc.nextInt();
    sc.nextLine();
    while(k-->0)
    {
        boolean t =false;
        int n=sc.nextInt();
        int l=sc.nextInt();

        int i,j,m;
        int a[]= new int[n];
        for(i=0;i<n;i++)
        {
            a[i]=sc.nextInt();

        }
        for(i=0;i<n-2;i++)
        {
            for(j=i+1;j<n-1;j++)
            {
                for(k=j+1;k<n;k++)
                {
                    if((a[i]+a[j]+a[k])==l)
                    {
                         t=true;
                        break;
                    }
                }
            }
        }
     String f=  t?"true":"false";
           System.out.println(f);
    }
    sc.close();

线程“main”中的异常

java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Solution.main(Solution.java:17)

示例输入

3
5 60
1 20 40 100 80 

样本输出错误

我尝试了什么?

if(sc.hasNextInt())
n=sc.nextInt();
if(sc.hasNextInt())
l=sc.nextInt();

对于假定的 hasNextInt() 修复,我得到了更多重复的输出(即错误)。

【问题讨论】:

  • 您是否在 IDE 调试器中单步调试您的代码以查看它实际在做什么?请这样做,这对你来说会更有教育意义。如果您这样做了但仍然不明白,请准确解释您在调试时发现的内容以及您不理解的内容。

标签: java exception error-handling


【解决方案1】:

在开始时放置一个迭代,并检查如下条件:

do {
//Here the code
} while (i.hasNextInt());

对于扫描仪错误,您应该检查扫描仪是否有这样的错误

Scanner sc =new Scanner(System.in);
if (sc.hasNext()) {
//here the code
}

【讨论】:

    【解决方案2】:
    3
    5 60
    1 20 40 100 80 
    false
    

    这是我在运行您的代码后得到的。我猜你的代码是正确的。但是你没有给它输入。

    java.util.NoSuchElementException 在扫描仪找不到您要求它读取的内容时抛出。

    给出完全正确的输入。

    【讨论】:

      【解决方案3】:

      您的代码中似乎已经关闭了扫描仪。不要关闭它并在程序中重新实例化它,而是在主程序开始时初始化一次并在主程序结束时关闭它。

      扫描器在其资源关闭时关闭,因为它实现了 可关闭的界面。

      如下例 -

        public static void main(String[] args) throws IOException {
              Scanner scanner = new Scanner(System.in);
              System.out.println(System.in.available());
              scanner.close();
              scanner = new Scanner(System.in);
              // System.out.println(System.in.available());
              // If you uncomment above: It will give you java.io.IOException: Stream closed
              String str = scanner.nextLine();
        }
      

      从帖子中得出这个答案:java.util.NoSuchElementException - Scanner reading user input

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多