所以我有这样的代码,用户输入一个从 0 到 9 的随机数,并且必须猜测这个数字,但我想将用户的尝试限制为 4 次,一旦他猜错 4 次,系统就会停止并显示一条消息“you超出了您允许的试验”这是我到目前为止的代码:
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();
}
最佳答案
还可以用你count
变量来跟踪尝试,一旦用户以限制结束,您可以通过打破 while
退出程序使用 break
循环陈述。
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
// TODO Auto-generated method stub
int nb,x;
int count= 1;
Scanner inp= new Scanner(System.in);
nb= (int)(Math.random()*10);
System.out.print(nb);
System.out.print("Guess the number between 0 and 9:");
x=inp.nextInt();
while(x!= nb) {
if (count <= 3){
if(x>nb) System.out.println("Lesser");
else if (x<nb) System.out.println("Bigger");
System.out.println("Try another Number");
x=inp.nextInt();
}
else{
System.out.print("you exceeded your allowed trials");
break;
}
count++;
}
System.out.println("Found!!");
System.out.println("Number of Guesses:" +count);
inp.close();
}
}
关于java - 在java代码中添加一个条件,用户只能尝试4次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60866338/