繁体   English   中英

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM