Java 为什么这个while循环没有终止?比较整数

Java 为什么这个while循环没有终止?比较整数,java,while-loop,Java,While Loop,我正在尝试创建一种菜单。如果没有选择菜单中的任何选项,则应继续重复这些选项。然而,这个while循环并没有终止,我不知道为什么 我怀疑这与我比较INT的方式有关 Scanner s = new Scanner(System.in); int inp = s.nextInt(); while (inp != 1 || inp != 2 || inp != 3 || inp != 4) { System.out.println("Not one of the options");

我正在尝试创建一种菜单。如果没有选择菜单中的任何选项,则应继续重复这些选项。然而,这个while循环并没有终止,我不知道为什么

我怀疑这与我比较INT的方式有关

Scanner s = new Scanner(System.in);
int inp = s.nextInt();

while (inp != 1 || inp != 2 || inp != 3 || inp != 4) {
    System.out.println("Not one of the options");
    System.out.println("Please choose an option:");
    System.out.println("\t1) Edit Property");
    System.out.println("\t2) View More info on Property");
    System.out.println("\t3) Remove Property");
    System.out.println("\t4) Return");

    s = new Scanner(System.in);
    inp = s.nextInt();
}
尝试将| |替换为&&如下所示:

  while(inp != 1 && inp != 2 && inp != 3 && inp != 4 ){
因为| |的第一个条件总是正确的

inp != 1 || inp != 2
这种情况总是正确的:

如果inp为42,则第一个操作数为真,第二个操作数也是真,因此结果为真 如果inp为1,则第一个操作数为false,第二个操作数为true,因此结果为true 如果inp为2,则第一个操作数为真,第二个操作数为假,因此结果为真 你想要的是&,而不是| |

或者你也可以使用

while (!(inp == 1 || inp == 2 || inp == 3 || inp == 4))
或更简单:

while (inp < 1 || inp > 4)

您需要使用&&进行检查。无论输入的是什么,4个or语句中至少有3个是真的,因此循环将再次循环

或者使用&&选择其他答案,您可以拉出否定,因为您想检查,而不是这些选项中的任何一个,即不是这个或那个或什么

while (!(inp == 1 || inp == 2 || inp == 3 || inp == 4))) {

}

你的情况是错误的

这:

while (inp != 1 || inp != 2 || inp != 3 || inp != 4) {
必须由

while (inp != 1 && inp != 2 && inp != 3 && inp != 4) {