adamH adamH - 26 days ago 8
Java Question

Java loop issue involving char and String

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.

Answer

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.

Comments