write a program that makes the computer guess the number you are thinking of the computer will ask you to enter a number between 100 and 200 then will randomly try to guess ( using a Random number generator) . the program will keep track of how many times it takes for the computer to guess the number and will print out the number of guesses at the end.
这就是我所做的:
import java.util.Random;
import java.util.Scanner;
public class fianl {
public static void main(String[] args)
{
Scanner keyboard=new Scanner(System.in);
Random rdm=new Random();
int guessnum=rdm.nextInt(70-20+1)+20;
System.out.println("Guess the number between 100 and 200");
int i=0,temp;
do
{
temp=keyboard.nextInt();
i++;
}
while(guessnum!=temp);
System.out.println("user has taken "+i+" chances to guess:"+guessnum);
keyboard.close();
}
}
最佳答案
你的逻辑有问题。计算机只会猜测 20 到 70 之间的数字,但用户输入的是 100 到 200 之间的数字。此外,您正在猜测计算机的编号,而不是相反。我也清理了你的代码一点。
import java.util.Random;
import java.util.Scanner;
public class ComputerGuesser {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Random random = new Random();
int computerGuess = 100 + random.nextInt(200-100+1);
int guesses = 0;
System.out.println("Enter a number from 100 to 200: ");
int guess = Integer.parseInt(scan.nextLine());
scan.close();
while (computerGuess != guess)
{
computerGuess = 100 + random.nextInt(200-100+1);
guesses++;
System.out.println("Guesses: " + guesses + ", Computer Guess: " + computerGuess + ", Your Guess: " + guess);
}
}
}
关于java - 不知道用户什么时候才能停止猜测呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30158060/