Help in hangman game

Joined
Jul 24, 2023
Messages
1
Reaction score
1
import java.util.*;

public class Main {
public static ArrayList<Character> rWordChAr = new ArrayList<>(); //system generated
public Character user; // user input
public static ArrayList<Character> gChar = new ArrayList<>(); //array to store chars if it matches


public static void main(String[] args){


Main m = new Main();
m.randWord();

do {
m.takingUserInput();
m.game();
System.out.println(gChar);
System.out.println(rWordChAr);
} while (!gChar.containsAll(rWordChAr));

System.out.println("congrats u have guessed the word");



}

void takingUserInput() {

Scanner scan = new Scanner(System.in);
System.out.print("guess a letter:");
String userIN = scan.next().toLowerCase();
System.out.println(userIN);
user = userIN.charAt(0);
// System.out.println(user);

}

void randWord() {
System.out.println("hello");
String[] words = {"strawberry","cat","dog","mountain","level"};

// for (String s : words) {
// System.out.println(s);
// }

// System.out.println(words.length); // length of array

Random rand = new Random();
int randInd = rand.nextInt(0, words.length); //creating random index number upper bound exclusive
System.out.println(randInd);

String rWord = words[randInd];
System.out.println(rWord); // random word generated
int length = rWord.length();

System.out.println("The word has "+length+ " letters");

char [] rWordAr = rWord.toCharArray(); //storing rand word in char array

for (int i=0; i<rWordAr.length;i++) {

rWordChAr.add(rWordAr); //adding letters to Character arraylist

}
System.out.println(rWordChAr);

}

void game() {

// for (char s : rWordChAr) {
// System.out.println(s);
// }

for (Character c : rWordChAr) { //iterate through the arraylist

if (user.equals(c)) {
System.out.print(user);
gChar.add(user);

} else {
System.out.print("_");
}


}
System.out.println();

}


}

****************************
I am trying to code a hangman game everything is working fine but but when I guess second letter it doesn't display the first letter I guessed.
example: the word is dog
i press : d
output: d _ _
again i press: o
output : 0
but it should be : do_

something maybe wrong with the looping I am new pls help
 
Joined
May 23, 2022
Messages
4
Reaction score
1
check the character in gChar and print it

// in game()
for (Character c: rWordChAr) {
if (gChar.contains(c) ) {
System.out.print(c);
continue;
}
...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,058
Latest member
QQXCharlot

Latest Threads

Top