gpt4 book ai didi

java - 当我想从键盘读取内容时,出现 java.util.NoSuchElementException

转载 作者:行者123 更新时间:2023-11-30 02:02:37 25 4
gpt4 key购买 nike

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

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");
}
}

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

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 HelloWorld.main(HelloWorld.java:25)

我该如何解决这个问题?

最佳答案

您必须使用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());
}

关于java - 当我想从键盘读取内容时,出现 java.util.NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52343185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com