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();
        triesNum++;

        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" );
    }

}

Recommended Answers

All 8 Replies

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
}
else
{
    // new guess
    // add it to the set of guessed numbers
    guessedNumbers.add(userGuess);
}

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 :)

commented: As long as the list doesn't become too large that's a fine solution. +0

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.

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

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 );           

      do    
      {  

        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.";    

        JOptionPane.showMessageDialog(null,losMsg);             
        }  
        else  {// other wise you won   
            String winMsg = "You Win !! " +
                              "\nThe secret number is " +  secretNumber+  
                              "\n\nNumber of guesses was " + numGuesses;  
        JOptionPane.showMessageDialog(null,winMsg);  

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

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...

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.