代码之家  ›  专栏  ›  技术社区  ›  Leo Messi

我明白了java.util.NoSuchElementException异常当我想从键盘上读东西的时候

  •  1
  • Leo Messi  · 技术社区  · 6 年前

    我想做一个简单的应用程序,从键盘上读取一个字符串,然后打印一条消息。这是我的密码:

    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异常在 java.util.Scanner文件throwFor先生(Scanner.java:862)在 java.util.Scanner文件.下一个(Scanner.java:1485版本)在 java.util.Scanner文件.nextInt公司(Scanner.java:2076版本)在 你好世界.main(java:25)

    我怎样才能解决这个问题?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Tony Stark    6 年前

    你必须使用 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
  •  1
  •   The Scientific Method    6 年前

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

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

    read at this link