I'm working on a project for school and was curious
whether there is a better way to perform some the
logic in my hangman program. It plays like hangman
but you can't lose depending on the number of moves.
import java.util.*; class Hangman { static Scanner scan = new Scanner(System.in); static Random rand = new Random(); static boolean isIn(char c, String str) { int occurrence = str.indexOf(c); if (occurrence >= 0) return true; else return false; } static boolean printCurrStatus(String strToGuess, String userInputs) { String current = ""; String positionTemp = ""; String currentTemp = ""; for (int i = 0; i < strToGuess.length(); i++) { current += "_" + " "; positionTemp += strToGuess.charAt(i) + " "; } for (int i = 0; i < userInputs.length(); i++) { char input = userInputs.charAt(i); if (isIn(input, strToGuess)) { int index = 0; int position = 0; while (index > -1) { index = positionTemp.indexOf(input, position); if (index < 0) break; else { currentTemp = current.substring(0, index) + input; currentTemp += current.substring(index + 1, positionTemp.length() - 1); current = currentTemp; position += 1; } } } } System.out.println(current); if (current.indexOf('_') < 0) return true; else return false; } static String getNextWordToGuess() { String[] nextWord = { "elephant", "tiger", "monkey", "baboon", "barbeque", "giraffe", "simple", "zebra", "porcupine", "aardvark" }; int newRandom = rand.nextInt(nextWord.length); return nextWord[newRandom]; } static void playGame() { String userInput = ""; String wordToGuess = getNextWordToGuess(); while (!printCurrStatus(wordToGuess, userInput)) { System.out.println("Enter next letter:"); userInput += scan.next(); } } public static void main(String[] args) { String choice = "y"; while (choice.equals("y")) { playGame(); System.out.println("Do you want to play again? (y or n)"); choice = scan.next(); } System.out.println("Thanks for playing!"); } }
Everything works fine but I'm curious on whether there
is a way to simplify the printCurrStatus method. I do not
want to change this method into multiple methods.
I'm new to the site and appreciate your time. I hope to
be a contributor soon.