1.读数值
正如胡安的评论所建议的,您没有阅读用户输入值。基本上,这是通过nextInt() 方法完成的。此外,int 是原始类型,必须初始化。您选择值 0。那么为什么不选择 101 以使其以不正确的值开始呢?那么你确定while循环会被触发:
public static void main(String... aArgs) {
Scanner sc = new Scanner(System.in);
// initialise at 101 to trigger the while loop
int userInput = 101;
// as we start at 101, it will enter the loop at least once
while (userInput > 100) {
System.out.println("Enter a number (<100):");
userInput = sc.nextInt();
}
System.out.println("Your number < 100 is: " + userInput);
}
2.永远不要相信用户
2.1 异常捕捉
以上代码可能足以完成您的作业。但是,为了学习,我有一个基本原则:永远不要相信用户!。如果前面的例子,如果用户输入azerty,那么你的程序会抛出一个InputMismatchException。那是什么?这个错误告诉你扫描器需要一个int,而你给他喂了别的东西:它抛出了这个。
一个简单的类比是:扫描仪只能吃苹果。你给了他一个梨子:他吃了一点,然后吐了出来:“我只能吃苹果”。为了防止你的扫描仪吐出来,你可以问他:“试试看,如果这不是苹果,我们试试别的吧”
在代码中,它为您提供如下内容:
public static void main(String... aArgs) {
Scanner sc = new Scanner(System.in);
// initialise at 101 to trigger the while loop
int userInput = 101;
// as we start at 101, it will enter the loop at least once
while (userInput > 100) {
// tell the scanner to try something
try {
System.out.println("Enter a number (<100):");
userInput = sc.nextInt();
}
// if the input is not a number, tell him do this this:
catch (InputMismatchException e) {
System.out.println("This is not a number!");
}
}
System.out.println("Your number < 100 is: " + userInput);
}
如果你对try/catch子句不熟悉,可以阅读this
2.1 扫描器进纸
上面的代码不工作。如何?如果你输入不是数字的东西,比如“aaaa”,你会得到无限的
输入一个数字(
这不是数字!
为什么?因为扫描仪没有抛出你的输入。基本上,他要么应该吃梨(但他会呕吐),要么把它扔到垃圾箱里,但你从来没有告诉他把它扔到垃圾箱里!扫描器需要在尝试下一个输入之前消耗输入。
简而言之:
-
userInput 从 101 开始,因此进入了 while 循环
- 你输入
aaaa。
-
InputMismatchException 被捕获。 “这不是一个数字!”打印出来
- userInput 值没有改变(仍然是 101),所以循环继续进行
- 在这个阶段,扫描器没有消耗上一个输入,所以下一个输入仍然是
aaaa。
- 转到 3. 重新开始
如何解决这个问题?通过next() 告诉扫描器使用输入:
public static void main(String... aArgs) {
Scanner scnr = new Scanner(System.in);
// initialise at 101 to trigger the while loop
int userInput = 101;
// as we start at 101, it will enter the loop at least once
while (userInput > 100) {
// tell the scanner to try something
try {
System.out.println("Enter a number (<100):");
userInput = scnr.nextInt();
}
// if the input is not a number, tell him do this this:
catch (InputMismatchException e) {
// consume the incorrect input with scnr.next()
// so that user can enter another input
System.out.println(scnr.next() + " is not a number!");
}
}
System.out.println("Your number < 100 is: " + userInput);
}