这是我的代码:
import java.util.*;
public class Game {
public static void main(String[] args) {
Random rand = new Random();
Scanner scan = new Scanner(System.in);
boolean guessed = false;
int randInt = rand.nextInt(10000) + 1;
System.out.println("Guess my number. It's between 1 and 10,000.");
while (!guessed) {
int guess = 0;
do {
if(!scan.hasNextInt()) {
String notInt = scan.next();
System.out.printf("%s is not an integer.\n", notInt);
}
else
guess = scan.nextInt();
}while (guess == 0);
if(guess > randInt) {
System.out.println(guess + " is too high.");
}
else if(guess < randInt) {
System.out.println(guess + " is too low.");
}
else if (guess == randInt) {
System.out.println(guess + " is the number!");
guessed = true;
}
}
}
}
这是数字猜测游戏,计算机生成1到10,000之间的随机数,用户必须通过提示猜测它。 我的问题是如何在每次猜测后让控制台输出新的猜测范围? 假设用户猜测5000并且控制台说“5000太高了”。 在猜测之后,我希望有一个猜测范围的打印。 由于5000太高,我想控制台打印 猜猜是在1到5000之间。 然后让我们说用户猜测400.“400太低了。” 猜猜是在400到5000之间。 在每次猜测后,我需要做些什么才能使控制台打印新的猜测范围? 谢谢。
答案 0 :(得分:2)
您可以通过执行以下操作来优化代码:
import java.util.Random;
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Random rand = new Random();
Scanner scan = new Scanner(System.in);
int randInt = rand.nextInt(10000) + 1;
int max=10000, min=1, counter=1;
while(true){
try{
System.out.printf("Guess my number. It's between %d and %d:\n", min, max);
int guess = Integer.parseInt(scan.nextLine());
if((guess>randInt && guess<=10000)){
System.out.println(guess + " is too high!");
max=guess;
}
else if(guess<randInt && guess>=1){
System.out.println(guess + " is too low!");
min=guess;
}
else if(guess==randInt){
System.out.println(guess + " is the number! After " + counter + " attempt");
break;
}
counter++;
}
catch(NumberFormatException e){
System.out.println("Please Insert Only Integers!");
continue;
}
}
scan.close();
}
}
<强>测试强>
如何运作?
max
或min
值。boolean
变量。答案 1 :(得分:0)
你可以有两个整数,upperRange和lowerRange。每当用户猜测太高时,将upperRange设置为用户的猜测。同样适用于lowerRange。
int upperRange;
int lowerRange;
if(guess > randInt) {
System.out.println(guess + " is too high.");
upperRange = guess;
} else if(guess < randInt) {
System.out.println(guess + " is too low.");
lowerRange = guess;
}
System.out.println("Guessing range: " + lowerRange + "-" + upperRange);