这个 while 语句有什么问题?

What's the problem in this while statement?

所以我是一个初学者,我 3 天前刚开始,我想在 java 中做一个 While 语句,但我似乎找不到没有 not 的循环方法在 while 块中再次让用户输入,我在这段代码中的想法是询问用户想要的操作,如果它是空的或没有可用的操作,程序将给他一条错误消息然后循环程序

import java.util.*;

public class calc{
    public static void main(String[] args) {
        Scanner sc = new Scanner (System.in);
        System.out.println("1.Sum\n2.Subtraction\n3.Multiplication\n4.Division");
        int oper = sc.nextInt();
        while (oper > 4 || oper < 1) {
            System.out.println("Please enter a valid number");
            System.out.println("1.Sum\n2.Subtraction\n3.Multiplication\n4.Division");
            int oper = sc.nextInt();
        }
    }
}

唯一真正错误的是第二个int oper = sc.nextInt();。您已经在范围内获得了一个变量 oper,您不能声明另一个。

删除 int.

您可能想要考虑重组循环,这样您就不必重复消息和扫描仪的读数:

int oper;
while (true) {
  System.out.println("1.Sum\n2.Subtraction\n3.Multiplication\n4.Division");
  oper = sc.nextInt();

  if (oper >= 1 && oper <= 4) {
    break;
  }

  System.out.println("Please enter a valid number");
}