所以我必须询问用户他们是否超过18岁,他们必须回答是真还是假。并保持循环直到他们输入正确的输入
到目前为止,我有这个
boolean b = false;
do {
try {
System.out.print("Are you above 18?");
Scanner n = new Scanner(System.in);
boolean bn = s.nextBoolean();
if (bn == true) {
// do stuff
} else if (bn == false) {
// do stuff
}
} catch (InputMismatchException e) {
System.out.println("Invalid input!");
}
} while (!b);
然而,它不会工作,因为循环继续前进,它不会读取输入权并执行我的if语句。我该如何解决?谢谢!
答案 0 :(得分:1)
对您的计划稍作调整。这有效
boolean b = false;
do {
try {
System.out.print("Are you above 18?");
Scanner n = new Scanner(System.in);
boolean bn = n.nextBoolean();
if (bn == true) {
System.out.println("Over 18");
} else if (bn == false) {
System.out.println("under 18");
}
} catch (InputMismatchException e) {
System.out.println("Invalid input!");
}
} while (!b);
输出
Are you above 18?true
Over 18
Are you above 18?false
under 18
Are you above 18?
答案 1 :(得分:1)
您需要重新检查您的扫描仪声明和初始化声明...
Scanner n = new Scanner(System.in);
boolean bn = s.nextBoolean();
应该是
Scanner n = new Scanner(System.in);
boolean bn = n.nextBoolean();
答案 2 :(得分:0)
尝试更改
boolean bn = s.nextBoolean();
到
b = s.nextBoolean();
答案 3 :(得分:0)
使用 -
scanner.nextBoolean()
do{
try{
System.out.print("Are you above 18?");
Scanner scanner = new Scanner(System.in);
if(scanner.nextBoolean()==true)
//do stuff
}else{
//do stuff
}
}