Scanner.hasNext() 在线编译时返回 false,但在 eclipse 上编译时返回

我正在尝试解决一个竞争性编码问题,当我在 eclipse 或命令提示符下执行它时它工作正常,但是当我在网站上上传解决方案时它没有执行并在我第一次使用的行抛出 noSuchElementException来自用户的输入。我已经添加了导致问题的代码部分。


我试图在不同的在线编译器上使用 java 8 编译器版本执行它,但它仍然会抛出相同的错误。我也尝试过使用 BufferedReader 但出于某种原因,代码将 k 的值打印为 -1。


import java.util.Scanner;


public class Solution {   

      public static void main(String[] args) {

        Scanner sc=new Scanner(System.in); 

        if(!sc.hasNext()){

            System.out.println("hasNext returns false");          

        }

        int k=sc.nextInt(); 

         System.out.println(k);

      }

}

输出:


hasNext returns false    

Exception in thread "main" java.util.NoSuchElementException

    at java.util.Scanner.throwFor(Scanner.java:862)

    at java.util.Scanner.next(Scanner.java:1485)

    at java.util.Scanner.nextInt(Scanner.java:2117)

    at java.util.Scanner.nextInt(Scanner.java:2076)

    at Solution.main(Solution.java:9)


人到中年有点甜
浏览 115回答 3
3回答

智慧大石

在这里你正在检查 sc.hasNext() 并且它会打印“hasNext returns false”但是在这之后你再次得到 nextInt() 它不会在那里因为在在线编译器中你无法在运行时传递参数。尝试这个,public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        if(!sc.hasNext()){            System.out.println("hasNext returns false");                  } else {        int k=sc.nextInt();          System.out.println(k);        }      }

米琪卡哇伊

也许您应该使用静态方法,例如:nextInt(); nextLine(); nextDouble(); nextBoolean();

慕慕森

我认为如果您正在使用一些在线编译器,您手头就没有标准输入流。只需像这样模拟您的输入:Scanner sc = new Scanner("42");尽管您检查过hasNext()返回 false,但您仍在尝试读取导致异常的下一个 int。上面有一段代码注释java.util.Scanner.throwFor()似乎证实了这一点:// If we are at the end of input then NoSuchElement; // If there is still input left then InputMismatch
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java