Reputation: 107
I am making a java program similar to hangman game.
the program first generates a random Word from my string Array.
then the user must type a letter. if the Word has the letter in it, it asks for Another letter, until the player has typed all letters correct.
if the letter the user typed, doesn't fit in in the Word, then the the program is supposed to add a +1 to a int variable named, letterWrong. when letterWrong is 2 the image should change. when its 3 it should change when its 4 it should change when its 5, game is over.
here is the issue: when i type a letter, the program loops and checks wheter the Word contains that letter. if it does, then the program shows the letter.
the issue comes when the letter doesn't fit that Word. because, i must make sure that the word doesn't contain that letter and if it doesn't then i must add a +1 to the int variable letterWrong. problem is the +1 is within the loop. i must have it outside the loop. but i cant fix that.
here's the code:
char word = edittext.getText().charAt(0);
for(int i = 0; i<randomWord.length(); i = i+1){
if(randomWord.charAt(i)==word){
textviewArray[i].setText(""+randomWord.charAt(i));
}
}
what is the best way, to check wheter the word contains that particular letter, and if it doesnt, then it should add a +1 to the int variable. the way i did it Before, it adds more than +1 to the int variable since its within the loop.
Upvotes: 0
Views: 100
Reputation: 41
As Itamar Green said, you can use String.contains()
method to check if randomWord
contains the letter. If it does contain the letter, show the letter. If it doesn't, increment letterWrong
.
char word = edittext.getText().charAt(0);
if(randomWord.contains(word){
textviewArray[i].setText(""+randomWord.charAt(i));
} else {
letterWrong++;
}
Upvotes: 0
Reputation: 4122
You can use String.contains()
:
String a =String.valueOf(word);
String s = randomWord;
if(s.contains(a)){
//preform actions
...
This will make word
to a string. I didn't write the whole code so as to leave room for adaptation.
Upvotes: 4
Reputation: 73
If I got it right you can try this:
char word = edittext.getText().charAt(0);
boolean flag = false;
if(randomWord.indexOf(word ) > -1) {
textviewArray[i].setText(""+word);
} else {
++letterWrong;
flag = true;
}
if(flag && letterWrong > 1) {
changeImage();
}
Upvotes: 0