【发布时间】:2016-04-06 19:48:06
【问题描述】:
这个条件语句(来自 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()) 检查。
我在语句的逻辑流程中遗漏了什么?
【问题讨论】:
-
不要依赖于你“在想什么”。 Java 中的每个类都有documentation。它准确地说明了这些方法的作用。如果它没有提示用户进行额外输入,则不会发生这种情况。
-
一种方法检查 int 是否存在,而另一种方法实际使用它。另外,您不必猜测或假设。所有内置类都是开源的。
-
When the program runs and I provide an integer as an input, I'm NOT prompted for another input。这是因为您尚未对其进行编程以要求第二个输入。查看loops,或添加更多代码以请求其他输入。 -
我想我现在明白了。在这个简化的代码中: Scanner test = new Scanner(System.in); System.out.println("请输入一个数字:"); test.hasNextInt(); test.hasNextInt();提示用户输入并根据用户的输入确定是否返回布尔值。我很困惑,因为我误解了文档所说的内容,并认为 hasNextInt() 方法只是查看现有输入,而不是提示用户(在此示例中)输入并对其进行评估。谢谢大家!