【问题标题】:I get java.util.NoSuchElementException when I want to read something from the keyboard [duplicate]当我想从键盘读取某些内容时,我得到 java.util.NoSuchElementException [重复]
【发布时间】:2019-02-19 22:17:31
【问题描述】:

我想制作一个简单的应用程序,它可以从键盘读取一个字符串,然后打印出一条消息。这是我的代码:

import java.util.Scanner; 

public class HelloWorld {   
    public static void main(String argv[]) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("enter an integer");
        int myint = keyboard.nextInt();
        System.out.println(myint+ " <- that's the string");     
    }    
}

出了点问题,因为我收到一条错误消息:

线程“main”中的异常 java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:862) 在 java.util.Scanner.next(Scanner.java:1485) 在 java.util.Scanner.nextInt(Scanner.java:2117) 在 java.util.Scanner.nextInt(Scanner.java:2076) 在 HelloWorld.main(HelloWorld.java:25)

我该如何解决这个问题?

【问题讨论】:

  • 你的意见是什么??
  • 我不能写任何东西,当我编译代码时我得到了那个消息
  • 您在使用 BlueJ 吗?终端似乎有问题。 stackoverflow.com/questions/47126927/… 。从命令行编译并运行程序并检查。它适用于 Eclipse。
  • 我复制了您的代码并在 Eclipse IDE 中运行。对我来说效果很好。
  • @rishabhagarwal 你是对的。我尝试了一个 java 在线小提琴,但它没有用,但我在 eclipse 中再次尝试,它确实有效

标签: java


【解决方案1】:

您必须使用scanner.hasNext()scanner.hasNextInt()

  // find the next int token and print it
  // loop for the whole scanner
  while (scanner.hasNext()) {

     // if the next is a int, print "Found" and the int
     if (scanner.hasNextInt()) {
        System.out.println("Found " + scanner.nextInt());
     }
     // if no int is found, print "Not found" and the token
     System.out.println("Not found " + scanner.next());
  }

【讨论】:

    【解决方案2】:

    NoSuchElementException 如果没有更多可用的令牌,将被抛出。这是由于调用nextInt() 而不检查是否有任何可用整数引起的。为了防止这种情况发生,您可以考虑使用hasNextInt() 来检查是否还有可用的令牌。

    if( keyboard.hasNextInt() )
      int myint = keyboard.nextInt();
    

    read at this link

    【讨论】:

      猜你喜欢
      • 2013-01-22
      • 2016-07-05
      • 2013-04-06
      • 2013-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-09
      相关资源
      最近更新 更多