adamH adamH - 8 months ago 45
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){


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.


You can use String.contains():

String a =String.valueOf(word);
String s = randomWord;
    //preform actions

This will make word to a string. I didn't write the whole code so as to leave room for adaptation.