Question: Hello! I need to make a functioning hangman game, and I have tried with this code. However, if a user guesses a correct letter, it
Hello! I need to make a functioning hangman game, and I have tried with this code. However, if a user guesses a correct letter, it stills forms part of the hangman, and the letter does not show up on the lines. Please help fix the code to make the game work if you can! This is in Java. Thank you :)
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Player 1 enter a word"); String word = scan.nextLine(); String worddisp = ""; int programr_t = 0; int wordlen = word.length(); int hdeterminer = 0; String[] stringarr = word.split(""); String[] inputarray = new String[50]; String inputstring = ""; for (int i = 0; i < wordlen; i++) { worddisp = worddisp + "_ "; }
while (programr_t == 0) { for (int k = 0; k < wordlen + 50; k++) { boolean match = true; //boolean match should be reset to true after every input String hx = ""; String h0 = ""; String h1 = " O"; String h2a = " O |"; String h2b = " O -|"; String h2c = " O -|-"; String h3 = " O -|- A"; if (hdeterminer == 0) { hx = h0; } if (hdeterminer == 1) { hx = h1; } if (hdeterminer == 2) { hx = h2a; } if (hdeterminer == 3) { hx = h2b; } if (hdeterminer == 4) { hx = h2c; }
System.out.println("Player 2 guess a letter " + worddisp); System.out.println(hx); inputstring = scan.nextLine(); inputarray[k] = inputstring; if (inputarray[k] != null) { System.out.print("Guessed letters: " + inputarray[k] + " "); //this line should print all the guessed letters so far (stored in inputarray) } System.out.println(" "); //This line is a spacer for (int j = 0; j < wordlen; j++) { if (inputarray[k].equals(stringarr[j])) { //this checks the inputted letter against every letter of the original word (stored in stringarr) System.out.println("InputMatchedALetter (test only)"); match = true; } else if (inputarray[k] != stringarr[j]) { match = false; } } if (match == false) { hdeterminer++; } if (hdeterminer > 4) { programr_t = 1; k = k + 5000; //this line and the previous line stop the program once the hangman is complete System.out.println(" Player 2 loses " + h3); } } } } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
