有 Java 编程相关的问题?

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

向java代码中添加一个条件,用户只能尝试4次

因此,我有一个代码,用户输入一个从0到9的随机数,并且必须猜测这个数字,但我想将用户试验限制为4次,一旦他猜错了4次,系统就会停止,并显示一条消息“你超出了允许的试验次数”。这是到目前为止我的代码:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int nb,x;
    int count= 0;
    Scanner inp= new Scanner(System.in);
    nb= (int)(Math.random()*10);
    System.out.print("Guess the number between 0 and 9");
    x=inp.nextInt();

    while(x!= nb) {
        if(x>nb) System.out.println("Lesser");
        else if (x<nb) System.out.println("Bigger");
        System.out.println("Try another Number");
        x=inp.nextInt();
        count++;

    }

    System.out.println("Found!!");
    System.out.println("Number of Guesses:" +count);


    inp.close();

}

共 (2) 个答案

  1. # 1 楼答案

        while(x!= nb) {
            if(x>nb) System.out.println("Lesser");
            else if (x<nb) System.out.println("Bigger");
            System.out.println("Try another Number");
            x=inp.nextInt();
            count++;
            if(count == 4) {
                if(x == nb) break; // Leave the while loop and print "Found" message
                System.out.println("You exceeded your allowed trials");
                return; // Skip the message after the while-loop.
            }
        }
    
  2. # 2 楼答案

    您可以使用count变量验证错误答案的数量,然后使用System.exit(0)方法完成应用程序

    例如:

    if (count == 4 && x != nb) {
     System.out.println("you exceeded your allowed trials");
     //Terminate the application
     System.exit(0);
    }