有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在尝试失败后关闭

我试图有一个输入,要求我选择一个数字1-99,我也想有这个系统。在两次尝试失败后关闭(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) 个答案

  1. # 1 楼答案

    对失败的尝试使用计数器(代码更新):

    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

  2. # 2 楼答案

    您需要创建一个标志变量。。。比如:

    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循环,但我将由你决定

  3. # 3 楼答案

    为了拥有“这个”系统。关闭时,只需手动完成程序运行,即退出循环。A.查一下你的电话号码。B.设置一个布尔标志,并使while循环在该标志上。当它改变状态时,循环将结束,计算机将返回到它的状态