为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

人到中年有点甜 2023-03-23 16:34:16
我正在尝试解决一个竞争性编码问题,当我在 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)
查看完整描述

3 回答

?
智慧大石

TA贡献1946条经验 获得超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);

        }

      }


查看完整回答
反对 回复 2023-03-23
?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

也许您应该使用静态方法,例如:

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


查看完整回答
反对 回复 2023-03-23
?
慕慕森

TA贡献1856条经验 获得超17个赞

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

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


查看完整回答
反对 回复 2023-03-23
  • 3 回答
  • 0 关注
  • 104 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信