我在这项任务中遇到了麻烦(高中).这是一个数字猜谜游戏,我已经把它的大部分都放下了,但他希望我们在控制台上放置一系列数字.示例输出将是:
输入下限: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);
}
Run Code Online (Sandbox Code Playgroud)
}
如果你尝试它也无论如何也很难玩.我要感谢一些帮助,谢谢!
对于范围内的随机数,您有两种选择:
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;
Run Code Online (Sandbox Code Playgroud)
或者在java 1.7或更高版本中:
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
180 次 |
| 最近记录: |