gpt4 book ai didi

java - hasNextInt()在java中的使用

转载 作者:行者123 更新时间:2023-11-29 02:59:51 28 4
gpt4 key购买 nike

我是初学者,我对 hasNextInt() 的使用感到困惑。如果它检查输入,那么我们不应该在请求用户输入后使用它吗?但是,在下面给定的代码中,它与 if 语句一起使用。请指教。

import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);

System.out.println("Enter your number");
if (userInput.hasNextInt()) {
int numberEntered = userInput.nextInt();
System.out.println("You entered an integer");
} else {
System.out.println("you didn't enter an integer");
}
}
}

最佳答案

The java.util.Scanner.hasNextInt() method returns true if the nexttoken in this scanner's input can be interpreted as an int value inthe default radix using the nextInt() method. The scanner does notadvance past any input.

因此当用户按下“Enter”时将调用 Scanner,然后它会评估用户提供的下一个输入是否为 int。

关于java - hasNextInt()在java中的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35800872/

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