我是一个初学者,对使用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");
}
}
}
您使用它来测试用户的输入,因此可以确保在调用nextInt时不会出现异常,因为输入不是int,也不会使光标向前移动:
Scanner scanner = new Scanner(System.in);
if(scanner.hasNextInt()){
System.out.println(scanner.nextInt());
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句