i’d like to implement an achievement system to my random number guessing game but i failed to construct a valid logic for it.
i’d like it to have an achievement system to detect a 2 or 3 consecutive CORRECT answers.
whenever there is a correct answer, cons+1(cons is the variable im using for the “consecutive” functionality of my achievement system.
otherwise, cons-1 and life-1.
here’s my code below… i know for sure that the error in the logic is because the cons–; and the life–; is in the loop for SCANNING THE ARRAY for a match(the array is the one im using to store the 10 two-digit random numbers that will be the basis of the “correctness” of each answer. My purpose for adding the LOOP is that it will scan the array for a possible match.
NOTE: Thank you advance for your help!
here’s my code:
public void cmpans()
{
String txget;
txget=gametext.getText();
String pars;
int ans;
pars=gametext.getText();
ans=Integer.parseInt(pars);
for(int i=0; i<10; i++) //this is my "Array Scanner" Loop
{
if(ans==arr[i])
{
userscore=userscore+10;
lbscore.setText("Score: "+userscore);
ck[i].setSelected(true);
arr[i]=0000;
cons++;
gametext.setText("");
lblives.setText("life: "+life);
lbcons.setText("cons: "+cons);
}
else if(ans!=arr[i])
{
cons--; //this is the cons and life im talking about
life--;
if(cons==2)
{
lbachieve.setText("You're a GOOD GUESSER!");
userscore=userscore+20;
}
else if(cons==4)
{
lbachieve.setText("You're an AMAZING GUESSER!!");
userscore=userscore+50;
}
}
}gametext.setText("");
I believe your logic to be quite deeply flawed, if what I understood of your description is correct.
My assumption:
The user gives his guess, and you see if that guess exists in the array.
First of all, you’re decreasing the player score for each number that isn’t equal to his guess, meaning, even if he does get one right, he’ll have 9 wrong. Move that logic out of the for loop, just use a variable inside to check if he guessed or not, and then do your increasing and decreasing outside (once he has guessed, break out of the for).
Secondly, I don’t think you want to decrease cons after a wrong guess… if you want consecutive, each wrong guess should set cons to 0 again (he has to start over).
Thirdly:
You can simplify your logic greatly if you use a structure more suited for checking if a given value exists in that structure, like a Set, for instance:
Fill that set up, and then your logic would be reduced to:
Hope this helps.