我正在尝试创建一个随机数游戏,其中用户给出较低和较高的数字,程序询问他/她想要多少猜测,然后继续猜测数字。
Scanner s = new Scanner(System.in);
System.out.print("Enter a low number: ");
int min = s.nextInt();
System.out.print("Enter a high number: ");
int max = s.nextInt();
Random rand = new Random();
int value = rand.nextInt((max - min) + 1) + min;
System.out.print("The Random Number is " + value);
这会在给定的值之间找到一个随机值,我认为我需要一个for循环来猜测,但是找出如何做到这一点变得困难任何想法?
答案 0 :(得分:0)
在当前代码之前添加以下行:
Scanner s = new Scanner(System.in);
System.out.print("Enter the number of guesses: ");
int count = s.nextInt();
然后,将代码置于如下循环中:
for(int i=0; i<count; i++){
System.out.print("Enter a low number: ");
int min = s.nextInt();
System.out.print("Enter a high number: ");
int max = s.nextInt();
Random rand = new Random();
int value = rand.nextInt((max - min) + 1) + min;
System.out.print("The Random Number is " + value);
}
答案 1 :(得分:0)
You can do it in this way :-
Scanner s = new Scanner(System.in);
System.out.print("Enter a low number: ");
int min = s.nextInt();
System.out.print("Enter a high number: ");
int max = s.nextInt();
Random rand = new Random();
System.out.println("Enter no of guesses : ");
int noOfGuesses = s.nextInt();
for(int i=0; i < noOfGuesses; i++){
int value = rand.nextInt((max - min) + 1) + min;
System.out.print("\nThe Random Number is " + value);
}
Here is the output :- Enter a low number: 5
Enter a high number: 50
Enter no of guesses :
5
The Random Number is 45
The Random Number is 42
The Random Number is 40
The Random Number is 9
The Random Number is 12