Java如果语句失败,请返回并再次尝试

时间:2018-05-09 04:51:30

标签: java loops

Scanner scannerObject= new Scanner(System.in) ;
    System.out.println("Enter what maths to use:");
    System.out.println("Enter 1 for addition");
    System.out.println("Enter 2 for Subtraction");
    System.out.println("Enter 3 for multiplication");
    System.out.println("Enter 4 for Division");
    n1=scannerObject.nextInt();

    if(n1>4) {
        System.out.println("That is not an option. Please try again");

我希望如果n1> 4,它会再次询问

4 个答案:

答案 0 :(得分:1)

只需在循环中包装,然后使用else来打破

while(true){
Scanner scannerObject= new Scanner(System.in) ;
    System.out.println("Enter what maths to use:");
    System.out.println("Enter 1 for addition");
    System.out.println("Enter 2 for Subtraction");
    System.out.println("Enter 3 for multiplication");
    System.out.println("Enter 4 for Division");
    n1=scannerObject.nextInt();

    if(n1>4) {
        System.out.println("That is not an option. Please try again");
}
   else break; //this will make exit the loop
}

答案 1 :(得分:0)

所以,你可能想要同样的循环 - 可能从Control Flow Statements

开始

也许像......

int n1 = -1;
do {
    Scanner scannerObject = new Scanner(System.in);
    System.out.println("Enter what maths to use:");
    System.out.println("Enter 1 for addition");
    System.out.println("Enter 2 for Subtraction");
    System.out.println("Enter 3 for multiplication");
    System.out.println("Enter 4 for Division");
    n1 = scannerObject.nextInt();

    if (n1 > 4) {
        System.out.println("That is not an option. Please try again");
    }
} while (n1 < 1 && n1 > 4);

答案 2 :(得分:0)

您可以使用简单的布尔条件。

boolean conditionNotMet = true;
while(conditionNotMet){
Scanner scannerObject= new Scanner(System.in) ;
    System.out.println("Enter what maths to use:");
    System.out.println("Enter 1 for addition");
    System.out.println("Enter 2 for Subtraction");
    System.out.println("Enter 3 for multiplication");
    System.out.println("Enter 4 for Division");
    n1=scannerObject.nextInt();

    conditionNotMet = false;
    if(n1>4) {
        conditionNotMet = true;
        System.out.println("That is not an option. Please try again");
     }
}
//continue processing using valid n1...

答案 3 :(得分:0)

所以你必须有办法在if语句之后回到问题列表。最好的方法是将所有问题都放在一个循环中。

instance

希望这有帮助