我在接受这项任务时遇到了麻烦(高中)。这是一个数字猜谜游戏,我已经把它的大部分都放下了,但他希望我们在控制台上放置一系列数字。输出示例如下:
输入下限:4
输入上限:10
等等,基本上选择您希望计算机选择的特定数字范围。我只能在一个范围内(1-1000)编码,因为我无法弄清楚如何做他想做的事情。这是我的代码:
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
int randomNumber;
randomNumber = (int) (Math.random() * 999 + 1);
Scanner keyboard = new Scanner(System.in);
int guess;
do {
System.out.print("Enter a guess (1-1000): ");
guess = keyboard.nextInt();
if (guess == randomNumber)
System.out.println("Your guess is correct. Congratulations!");
else if (guess < randomNumber)
System.out.println("Your guess is smaller than the secret number.");
else if (guess > randomNumber)
System.out.println("Your guess is greater than the secret number.");
} while (guess != randomNumber);
}
}
如果你尝试的话,反正也很难玩。我将不胜感激,谢谢!
答案 0 :(得分:6)
对于范围内的随机数,您有两种选择:
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
或者在java 1.7或更高版本中:
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
答案 1 :(得分:0)
如果您希望用户设置范围,您需要实现另一条线路,向用户询问范围
Scanner min= new Scanner(System.in);
和Scanner max = new Scanner(System.in);
然后在您的代码randomNumber = (int) (Math.random() * 999 + 1);
的这一行中,您现在可以使用用户输入random.nextInt(max - min + 1) + min
设置您想要的范围
答案 2 :(得分:0)
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("enter minimum");
int min= keyboard.nextInt();
System.out.println("enter maximum");
int max= keyboard.nextInt();
int randomNumber= (int) (Math.random()* max + min);
int guess;
do {
System.out.print("Enter a guess (1-1000): ");
guess = keyboard.nextInt();
if (guess == randomNumber)
System.out.println("Your guess is correct. Congratulations!");
else if (guess < randomNumber)
System.out.println("Your guess is smaller than the secret number.");
else if (guess > randomNumber)
System.out.println("Your guess is greater than the secret number.");
} while (guess != randomNumber);
}
}