这个条件语句(来自 Udacity 的 Java 编程入门 | 问题集 4 | 问题 #20)是如何工作的?
import java.util.Scanner;
public class MonthPrinter {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a month number (1 through 12) ");
if (!in.hasNextInt()) {
System.out.println("Not an integer. Terminating");
} else {
int theMonthNumber = in.nextInt();
if (!(theMonthNumber >= 1 && theMonthNumber <= 12)) {
System.out.println("Number must be 1 through 12");
} else {
Month test = new Month(theMonthNumber);
System.out.print(test.getMonthName() + " " + test.getNumberOfDays());
}
}
}
}
第一个if (!in.hasNextInt())
检查用户输入是否为整数。如果它不是整数,则 main 方法将打印 Not an integer. Terminating
。这是完全有道理的。
但是,如果用户输入整数,代码将继续执行 else
语句,其中下一行代码是 int theMonthNumber = in.nextInt();
当程序运行并且我提供一个整数作为输入时,系统不会提示我输入其他输入。我认为 hasNextInt()
方法和nextInt()
方法应该请求用户输入。因此,系统应该提示我总共输入两个输入(假设我提供一个整数)。当我空运行这个场景时,我输入一个整数 3。这会传递 if(!hasNextInt())
检查。
我在语句的逻辑流程中遗漏了什么?
最佳答案
I'm thinking in my mind that both the hasNextInt() method and nextInt() method should request an input from the user.
否。Scanner.hasNextInt()
Javadoc 说(部分)
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the
nextInt()
method. The scanner does not advance past any input.
最后一句告诉您它不消耗int
。
关于java - hasNextInt() 和 nextInt() 方法流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34570133/