Java 扫描器和 if-else 语句

Java scanner and if-else statements

我如何使用一个简单的 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");

        }
    }
}
public static void main(String[] args) {
    // TODO Auto-generated method stub

    while (true) {
        if (insertNumber()) {
            break;
        }
    }

}

public static boolean insertNumber() {

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

    Scanner myInt = new Scanner(System.in);

    int choice = myInt.nextInt();

    if (choice <= 10) {
        System.out.println("acceptable");
        return true;

    } else {
        System.out.println("unacceptable");
        return false;
    }
}