如何在while循环中运行扫描器


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不是一个有效的输入,我想再次运行扫描器,直到他们输入一个有效的响应

What I tried:

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

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);
}

您还可以使用延伸的循环

‘{

//你的代码在这里

}而(条件)的

最新更新