尝试失败后关闭

时间:2018-02-20 22:17:34

标签: java

我正在尝试输入一个要求我选择1-99的数字,我想在2次尝试失败之后得到这个system.close(0),如果有人能帮助我,我将不胜感激。

package joey;

import java.util.Scanner;

public class Joey {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        while (true)   { 
            System.out.println("Please enter an number between 0-99: ");
            int n = input.nextInt();
            if ((n > 99) || (n < 1))
                System.out.println("Invalid number");
            else
                break;          
       }
    }
}

3 个答案:

答案 0 :(得分:0)

为了拥有''this''system.close,你只需要手动完成程序运行 - 也就是退出循环。所以A.检查你的号码。 B.设置一个布尔标志,并使while循环在该标志上显示。当它改变状态时,循环将结束,计算机将返回其状态。

答案 1 :(得分:0)

您需要创建一个标志变量......类似于:

int counter = 0;

然后将while (true) {循环更改为:

do {
    //Do whatever you want here
    counter++; //Don't forget to increase the counter or you'll end up with an infinite loop
    //If number is in range 1-99 then incorrect = false otherwise it becomes true
} while (counter < 2 && incorrect);

if (incorrect) {
    System.out.println("Good bye! You failed!");
} else {
    System.out.println("Good bye! You approved!");
}

无需System.exit(0);电话

或许您可以使用do-while循环,但我将其留给您

答案 2 :(得分:0)

使用计数器进行失败尝试(代码已更新):

import java.util.Scanner;
class Main {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        int failed = 0;

        while (failed < 2) {
            System.out.println("Please enter an number between 0-99: ");
            int n = input.nextInt();
            if ((n > 99) || (n < 1)) {
                System.out.println("Invalid number");
                failed += 1;
            } else {
                System.out.println("Correct! Closing now");
                return;
            }
        }        
        System.out.println("Finished after two failed attempts");
    }
}

看到它正常工作here