954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Creating a Guess Game were the Computer Guesses the User Number

Here is my code, for some reason it goes to an infinite loop when i try and adjust the highest and lowest values for the Math.Random() method. The code works fine if i do not try to change those values based on if the guess was higher or lower than the user's inputted number.

import java.util.Scanner;

public class ComputerGuess {

    public static void main(String [] args) {
    	Scanner reader = new Scanner(System.in);
    	int highestvalue= 100;
    	int lowestvalue=1;
    	int randomnum;
    	int user;
    	String line;
    	int temp;
    	int guesses=0;
		while (true){
		System.out.println("Enter number for computer to guess between 1 and 100.");
		user= reader.nextInt();
		if (user<=100&&user>=1)
			break;
		else
			System.out.println("Out of Range");

		}
    while (true){
    	guesses++;

         randomnum=(int)(highestvalue * Math.random()) + lowestvalue;

         if (user==randomnum)
         {
         	System.out.println("The Computer Guessed Correct! It took "+guesses+" guesses!"); break;
         	}
		temp=randomnum;
         if (randomnum<user)
         {highestvalue=temp;}
		
         if (randomnum>user)
         {lowestvalue=temp;}



    	}
    }


}
ryan400
Newbie Poster
2 posts since Oct 2010
Reputation Points: 10
Solved Threads: 0
 

Don't you have the logic for the change backward? Look at lines 34 and 35 and think carefully (by the way, why do you need variable temp ?

Related: You can always instrument your logic blocks with a print statement that shows where you are. When in an infinite loop, hit Ctrl-C and look at the output. You often get a very good idea right away.

griswolf
Veteran Poster
1,165 posts since Apr 2010
Reputation Points: 344
Solved Threads: 256
 

Thank you! Works Perfect now!

ryan400
Newbie Poster
2 posts since Oct 2010
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: