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



我正在尝试解决一个竞争性编码问题,当我在 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)

在这里你正在检查sc.hasNext((,它将打印"hasNext返回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);
        }
      }

我认为如果您使用一些在线编译器,您手头没有标准的输入流。只需像这样模拟您的输入:

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

也许你应该使用静态方法,比如:

nextInt();
nextLine();
nextDouble();
nextBoolean();

最新更新