您没有大括号,因此 while 循环循环通过 System.out.print 语句并且永远不存在。
如果按原样添加大括号,则在输入非/整数时将无法读取 int。
要正确读取整数,您必须循环询问下一个令牌,然后验证它是一个 int。
$cat Wt.java
import java.util.*;
class Wt {
public static void main( String ... args ) {
Scanner s = new Scanner(System.in);
System.out.print("Write a number: ");
while ( !s.hasNextInt()) {
System.out.print("Write a number: ");
s.next(); // <-- ask for the next and see if that was an int
}
int n = s.nextInt();
System.out.println("The number was: " + n );
}
}
$javac Wt.java
$java Wt
Write a number: one
Write a number: two
Write a number: tres
Write a number: 1.1
Write a number: f
Write a number: 42
The number was: 42