不知道如何阻止这种情况,同时循环无限重复。我用来检查用户输入是否是int。如果未输入 int,则循环将无限重复。hasNextIntpublic static void validatingInput(){ Scanner scan = new Scanner(System.in); boolean valid = false; int userNumber = 0; while(!valid) { System.out.println("Enter number between 1 and 20: "); if (scan.hasNextInt()) { userNumber = scan.nextInt(); valid = true; } else System.out.print("Not an int. "); }}
2 回答
沧海一幻觉
TA贡献1824条经验 获得超5个赞
您需要使用扫描程序中的令牌,以允许它读取下一个令牌:
while (!valid) {
System.out.println("Enter number between 1 and 20: ");
if (scan.hasNextInt()) {
userNumber = scan.nextInt();
valid = true;
} else
System.out.print("Not an int. ");
scan.next(); // Skip a token
}
}
添加回答
举报
0/150
提交
取消