提问人:jgrewal 提问时间:7/3/2022 最后编辑:jgrewal 更新时间:7/3/2022 访问量:61
如何在 while 循环中运行扫描程序
How to run scanner in a while loop
问:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("1 - login");
System.out.println("2 - regrister");
int firstSelection = scanner.nextInt();
while(firstSelection > 2 || firstSelection <1) {
System.out.println(firstSelection+" is not a valid entry");
int firstSelection = scanner.nextInt();
}
System.out.println("you picked "+firstSelection);
}
问题:
重复变量firstSelection
我想做什么:
- 要求用户输入
- 当 while 循环运行时。如果 firstSelection 不是有效的输入,我想再次运行扫描程序,直到他们输入有效的响应
我尝试过:
System.out.println("1 - login");
System.out.println("2 - regrister");
boolean fs;
while((fs = scanner.nextInt() != 1) || (fs = scanner.nextInt() != 2)) {
System.out.println(fs+" is not a valid entry");
}
System.out.println("you picked "+fs);
问题:
如果我输入 1。我没有收到印刷线说.如果我再次输入它,它会告诉我.
you picked 1
true is not a valid entry
如果我输入了不正确的响应,它将持续响应
true is not a valid entry
答:
2赞
SM. Hosseini
7/3/2022
#1
public static void main(String[] args) {
int firstSelection;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("1 - login");
System.out.println("2 - regrister");
firstSelection = scanner.nextInt();
if (firstSelection == 1 || firstSelection == 2)
break;
else {
System.out.println(firstSelection + " is not a valid entry");
System.out.println("---------------------");
}
}
System.out.println("you picked " + firstSelection);
}
1赞
Jay
7/3/2022
#2
您也可以使用 do-while 循环
'do{
您的代码在这里
}while(条件)'
下一个:开关案例未正确执行
评论