I need help to figure it out how to keep track of how many guesses the user is making and NOT allow the user to guess any value thet had already tried. tHANK YOU

import java.util.Random;
import java.util.Scanner;

public class GuessingRand {

    public static void main(String[] args) {

        Random rand = new Random();
        int guessNum = rand.nextInt(100);
        int triesNum = 0;

        Scanner input = new Scanner(System.in);
        int guess;
        boolean win = false;

        while (win == false) {

        System.out.println("Guess a number between 1 and 100:  ");
        guess = input.nextInt();

        if (guess == guessNum) {
            win = true;
            else if ( guess < guessNum ) {
            System.out.println("Your guess is too low");
        else if ( guess > guessNum) {
            System.out.println("Your guess is too high");
        System.out.println("You win!");
        System.out.println("The number was " + guessNum);
        System.out.println("It took you " + triesNum + " tries" );

5 Years
Discussion Span
Last Post by mvmalderen

Use a Set datastructure to keep track of the numbers already guessed.
Everytime the user makes a guess, you check if the user has guessed this number already by looking if that number is contained in the set.
If not, then the user hasn't guessed that number before and you add it to the set so that you can check if the user guesses that number again.

I'd recommend to use the HashSet implementation. Here's a quick example:

Set<Integer> guessedNumbers = new HashSet<Integer>();

int userGuess = ... ; // get input from user

if (guessedNumbers.contains(userGuess))
    // previous guess
    // new guess
    // add it to the set of guessed numbers

Edited by mvmalderen


How about throwing any guess the user makes into an ArrayList? That way, you can easily fetch amount of tries by running a myArrayList.size() (returns an integer on how big the arraylist is).

And every time the user attempts to make a guess, their guess is checked against the arraylist (myArrayList.contains(guess)). This should work fine for small to medium-sized arrays :)

Votes + Comments
As long as the list doesn't become too large that's a fine solution.

thank you guys for your inputs. I'll try your suggestion and see what works.


Use hashset if you don't allow user to enter same value again.
So to check if user has guessed number,no need to do anything just keep on adding all guess to set.
If number is already guessed,Set doesnot allow duplicacy so add() method will return False.

Votes + Comments
Yes, using the return value of add is a bit more efficient compared to explicitly calling contains() first :)

Well this is a rewrite code. Would any java gurus take a look at the code. Right now is working but I need to add a line to the output messages. For instance if the number from input already has key in the number twice, the msg will display " you already guessed the number #. Also would be easier to use array and how about to do it. Thank you.

import javax.swing.*;  

public class Eg04 {  

 public static void main(String[]  args)    {  
      final int  MAX = 100;      
      int secretNumber = (int)(Math.random() * MAX) + 1;   
      int guess;  
      int numGuesses = 0;  
      String openingMsg = "Chris's Guessing Game" +  
                            "\nPick a number between 1 and " + MAX ;  
      JOptionPane.showMessageDialog(null,openingMsg );           


        String input = JOptionPane.showInputDialog("A Secret number has been created between  1 and " + 
                                                     MAX + "\n\nGuess the number ?" );  
        guess = Integer.parseInt(input);  
        numGuesses += 1;  

        if (guess < 1 || guess > MAX)   
           JOptionPane.showMessageDialog(null,"Invalid guess - should be between 1 and " + MAX);   
            else if (guess > secretNumber)//creates the too high   
                JOptionPane.showMessageDialog(null, "Too High ! " + "\nNumber of guesses is: " + numGuesses);  
                else if (guess < secretNumber)//creates the too low   
                    JOptionPane.showMessageDialog(null, "Too Low ! " + "\nNumber of guesses is: " + numGuesses);  

      } while (guess != secretNumber && numGuesses<=4 );// while there is no match and your count is less than 3.  

        if (numGuesses > 4 && guess != secretNumber ){// if your number of guesses are above 4 you lose  

            String losMsg = "You Lose !! " +  
                                "\nMy secret number is " + secretNumber +  
                                "\n\nYou made " + numGuesses + " guesses.";    

        else  {// other wise you won   
            String winMsg = "You Win !! " +
                              "\nThe secret number is " +  secretNumber+  
                              "\n\nNumber of guesses was " + numGuesses;  

    } // end of counting loop      
  } // end main

Edited by toldav: code


thank you guys for your inputs. I'll try your suggestion and see what works.

I can't seem to spot any trial of given suggestions in the code you posted...

Edited by mvmalderen


Would any java gurus take a look at the code

Don't know if i count as a guru, but I can't see any obvious faults in that code.
IIM has already given you an excellent way to check if the same number is entered twice. Definitely easier than using an array.


Instead of writing: numGuesses += 1; you could use the postfix increment operator: numGuesses++;
That seems to be the common way of incrementing a counter by one.

Edited by mvmalderen

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.