我将如何使用Scanner进行简单的if-else语句来进行键盘输入,如何将整数与参数进行比较,如果不是期望的结果,会再次提示用户再次输入该整数?这就是我所拥有的,我认为这应该很容易,但是我只是在学习;

 public static void main(String[] args) {

    Scanner myInt = new Scanner(System.in);

    System.out.println("Enter a number between 1 and 10");

    int choice = myInt.nextInt();

    if (choice <= 10) {
        System.out.println("acceptable");
    } else {

                System.out.println("unacceptable");
                System.out.println("Enter a number between 1 and 10");

            }
        }
    }


关于如何处理此问题的任何提示?

谢谢!

最佳答案

您可以使用while循环不断询问数字并检查数字是否可接受:

public static void main(String[] args) {

    Scanner myInt = new Scanner(System.in);
    boolean acceptable=false;
    while(!acceptable){
        System.out.println("Enter a number between 1 and 10");

        int choice = myInt.nextInt();

        if (choice <= 10 && choice>=1) {
            System.out.println("acceptable");
            acceptable=true;
        } else {

            System.out.println("unacceptable");

        }
    }
}

10-04 23:23
查看更多