Hello, I am very new here (and to Java as a whole), so I apologize if I've made a mistake.
Basically, I'm asking for some advice on how I can make this code so that it is all within the same class, rather than working as 2 separate classes. This is a simple text-based hangman game. As of now, I have 2 separate files, one containing my main class, and one with the game class (containing all of the rules). Sorry if that doesn't make much sense, I'm not sure how to explain it better.
Here is the game class:
import java.util.Scanner; public class game { Scanner keyboard = new Scanner (System.in); public String secretWord; public String disguisedWord = ""; public String guessedLetters = ""; private int numberOfGuesses = 0; private int numberOfWrongGuesses = 0; public void setSecretWord(String secretWord) { this.secretWord = secretWord; for(int i = 0; i < secretWord.length(); i++) { this.disguisedWord += "?"; } } public boolean makeGuess(char guess) { guessedLetters += guess; String tempString = ""; numberOfGuesses ++; for(int i = 0; i < secretWord.length(); i++) { if(guess == secretWord.charAt(i)) tempString += guess; else tempString += disguisedWord.charAt(i); } if(!tempString.equalsIgnoreCase(disguisedWord)) { disguisedWord = tempString; return true; } else { numberOfWrongGuesses++; return false; } } public String getDisguisedWord() { System.out.print("The disguisedWord is "); return disguisedWord; } public String getSecretWord() { return secretWord; } public void guessResponse() { if(numberOfGuesses > 0) { System.out.print("Guesses made " + numberOfGuesses + " times."); System.out.print(" with " + numberOfWrongGuesses + " wrong"); System.out.println("(" + guessedLetters + ")"); } System.out.println("Guess a letter: "); } public boolean isFound() { if (secretWord.equalsIgnoreCase(disguisedWord)) { System.out.println("Congratulations, you found the secret word: " + disguisedWord); return true; } else { return false; } } }
...and the main class:
import java.util.Scanner; public class Hangman { public static void main(String[] args) { Scanner keyboard = new Scanner (System.in); game hangman = new game(); System.out.println("Lets play Hang Man"); System.out.println("Enter secret word"); String secretWord = keyboard.next(); hangman.setSecretWord(secretWord); System.out.println(); while(hangman.isFound() == false) { System.out.println(hangman.getDisguisedWord()); hangman.guessResponse(); String guess = keyboard.next(); hangman.makeGuess(guess.charAt(0)); System.out.println(); } System.out.println(); System.out.println("Thanks for playing Hangman."); } }
My instructor suggested using a main method that looks more like the following, but I just don't have the capacity to understand how to make it work with what I've got.
public static void main(String[] args) { Hangman game = new Hangman(); game.initialize("Happiness"); System.out.println("Lets play a round of hangman."); game.playGame(); }
Thanks!