Henrik Varga
Henrik Varga

Reputation: 55

How to get the previous value of a variable

I made a program that thinks of a number and you have to guess the number. It is working well, but I got stuck. First of all, you (the player) has 10 tries in a round. Every wrong guess subtracts 1 from the tries. If you reach 0 you lose. The variable where the thing stores the randomized number looks like this:

int guess = Integer.parseInt(etGuess.getText().toString());

Of course I have an edittext field with the name etGuess.

So when the player enters the same number twice (for example: 5, then 5 again), the program subtracts 1 then again 1 (so 2) tries. I'd like to know how can I get the previous value of the guess integer and check whether it was already guessed or not.

I think of something like this:

if ( previous_guess != guess )

Upvotes: 0

Views: 804

Answers (2)

Pokechu22
Pokechu22

Reputation: 5046

Use a HashSet.

Here's how I would do this:

//Declare the variable outside of a function
HashSet<Integer> previousGuesses = new HashSet<Integer>();
//Check if it is already guessed
if (set.contains(guess)) {
     //Alert the user that they can't use this.
}
//Adding a variable to it in a function: 
set.add(guess);

Make sure to test if it contains before adding it or preforming any of the regular code.

Upvotes: 1

DrkStr
DrkStr

Reputation: 1932

Store all of your previous numbers in an array and then check the array then the player enters a new number.

Upvotes: 1

Related Questions