Reputation: 25
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.
this is what I did:
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();
}
}
Upvotes: 0
Views: 73
Reputation: 903
import java.util.Random;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Random random = new Random();
int start = 100;
int end = 200;
int seed =(end - start + 1);
int randomNumber = (random.nextInt(seed) + start);
int guessedNumber = 0;
int tries=0;
System.out.printf("The number is between %d and %d.\n", start, end);
do
{
tries++;
System.out.print("Guess what the number is: ");
guessedNumber = scan.nextInt();
if (guessedNumber > randomNumber)
System.out.println("Your guess is too high!");
else if (guessedNumber < randomNumber)
System.out.println("Your guess is too low!");
else{
System.out.println("You got it!");
System.out.println("You guessed: " + tries+ " times");
}
} while (guessedNumber != randomNumber);
}
}
Upvotes: 0
Reputation: 2618
Your logic is flawed. The computer will only guess a number between 20 and 70, but the user is inputting a number from 100 to 200. In addition you are guessing the computer's number, not the other way around. I cleaned up your code a little bit too.
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);
}
}
}
Upvotes: 1