Jump to content

Java programming help

namarino

So this program plays hangman. I'm having trouble with the letterReplacement method. It basically has to pick a word, then display blanks that correspond to the number of letter in the word and then prompt the user for a letter. If the letter is in the word, it has to be placed in the word in the right place. If it is not, you only get 6 turns, so it has to say, "You only have 5 more turn" and 4,3,2,1 as you keep guessing wrong. Can someone help me with this?

import java.util.Random;import java.util.Scanner;public class HangMan{    private static int wordChoice;    private static String displayedWord;    public static String pickWord(int wordChoice)    {        switch(wordChoice)        {            case 0:            displayedWord = "motherboard";            break;            case 1:            displayedWord = "case";            break;            case 2:            displayedWord = "powersupply";            break;            case 3:            displayedWord = "harddrive";            break;            case 4:            displayedWord = "mouse";            break;            case 5:            displayedWord = "keyboard";            break;            case 6:            displayedWord = "peripheral";            break;            case 7:            displayedWord = "graphicscard";            break;            case 8:            displayedWord = "processor";            break;            case 9:            displayedWord = "latency";            break;            case 10:            displayedWord = "ping";            break;            case 11:            displayedWord = "gaming";            break;            case 12:            displayedWord = "resolution";            break;            case 13:            displayedWord = "watercooling";            break;            case 14:            displayedWord = "cache";            break;            case 15:            displayedWord = "memory";            break;            case 16:            displayedWord = "chipset";            break;            case 17:            displayedWord = "intel";            break;            case 18:            displayedWord = "notebook";            break;            case 19:            displayedWord = "desktop";            break;            case 20:            displayedWord = "aliasing";            break;        }        return displayedWord;    }    public static void main(String[]args)    {        Scanner scan = new Scanner(System.in);        String userChoice;        int gameCount = 0;        int lostGames = 0;        System.out.print("Welcome to a game of hangman!");        System.out.print("Do you want to play? (Y/N): ");        userChoice = scan.next();        while (!userChoice.equalsIgnoreCase("n"))        {            switch (userChoice)            {                case "Y":                case "y":                Random wordPick = new Random();                wordChoice = wordPick.nextInt(20);                pickWord(wordChoice);                letterReplacement(displayedWord);                break;                             default:                System.out.println("Bad input.");                break;            }            gameCount++;            System.out.println("You have played " + gameCount + " games. Do you want to play again?");            userChoice = scan.next();        }    }    public static void letterReplacement (String displayedWord)    {        Scanner scan = new Scanner(System.in);        int wordLength = displayedWord.length();        int numberOfLetters = 0;        StringBuilder guessingWord = new StringBuilder();        while(numberOfLetters < wordLength)        {            guessingWord.append(" _ ");            numberOfLetters++;        }        System.out.println(guessingWord);        char guessedLetter;        int guessesLeft = 5;        int letter;        System.out.print("Please guess a letter: ");        while(guessesLeft > -1)        {            guessedLetter = scan.next().charAt(0);            for(letter = 0; letter < displayedWord.length(); letter++)            {                if(displayedWord.charAt(letter) == guessedLetter)                {                    guessingWord.deleteCharAt(letter + 1);                    guessingWord.insert(letter, guessedLetter);                    System.out.println(guessingWord);                }            }            guessesLeft--;        }    }}
Link to comment
Share on other sites

Link to post
Share on other sites

Please use code tags when posing code on the forum.

 

You can add code tags with the blue < > above the text box when you edit/post or manually add them around your code like so

[code]// Code goes between the tagspublic class Example {}[/code]
Link to comment
Share on other sites

Link to post
Share on other sites

 

Please use code tags when posing code on the forum.

 

You can add code tags with the blue < > above the text box when you edit/post or manually add them around your code like so

[code]// Code goes between the tagspublic class Example {}[/code]

Ok I edited it.

Link to comment
Share on other sites

Link to post
Share on other sites

Ok I edited it.

Appreciate it.

 

As for your problem, it's because the spaces you add with append(" _ ") also count as characters in your word. So the length of displayedWord and guessingWord aren't the same and therefore the index of the letter doesn't match.

// IfdisplayedWord = "test"; // length of 4// ThenguessingWord = " _  _  _  _ "; // length of 12// So the position of the letter 'e' is 1 in displayedWord but 5 in guessingWord

If you remove the spaces from append(" _ ") then they will match up. You then just need to fix up the delete and insert parts. Or, if you want to keep the spacing since it looks better, you can make it work by just changing where you delete and insert so that it factors in the spaces (letter*3+1).

 

I never thought of using a StringBuilder for this. Instead I would have used a character array (no need for you to switch yours though since it can work with a couple small changes).

// Set the secret wordString secretWord = "test";// Create a character array the same length as the secret wordchar[] hiddenWord = new char[secretWord.length()];// Fill that character array with a default characterArrays.fill(hiddenWord , '*');// Turn the character array into a string when you want to print itString revealed = new String(hiddenWord);System.out.println(revealed); // prints ****

That way, when you find a letter you can replace that location in the character array with the hidden word

hiddenWord[i] = letter;// ExamplehiddenWord[1] = 'e';System.out.println(new String(hiddenWord)); // prints *e**
Link to comment
Share on other sites

Link to post
Share on other sites

 

Appreciate it.

 

As for your problem, it's because the spaces you add with append(" _ ") also count as characters in your word. So the length of displayedWord and guessingWord aren't the same and therefore the index of the letter doesn't match.

// IfdisplayedWord = "test"; // length of 4// ThenguessingWord = " _  _  _  _ "; // length of 12// So the position of the letter 'e' is 1 in displayedWord but 5 in guessingWord

If you remove the spaces from append(" _ ") then they will match up. You then just need to fix up the delete and insert parts. Or, if you want to keep the spacing since it looks better, you can make it work by just changing where you delete and insert so that it factors in the spaces (letter*3+1).

 

I never thought of using a StringBuilder for this. Instead I would have used a character array (no need for you to switch yours though since it can work with a couple small changes).

// Set the secret wordString secretWord = "test";// Create a character array the same length as the secret wordchar[] hiddenWord = new char[secretWord.length()];// Fill that character array with a default characterArrays.fill(hiddenWord , '*');// Turn the character array into a string when you want to print itString revealed = new String(hiddenWord);System.out.println(revealed); // prints ****

That way, when you find a letter you can replace that location in the character array with the hidden word

hiddenWord[i] = letter;// ExamplehiddenWord[1] = 'e';System.out.println(new String(hiddenWord)); // prints *e**

Yeah I think the array would probably be better, but unfortunately we haven't learned arrays yet. We learn that it part two of the class :) I appreciate your help though! I'll be sure to ask you if I have any other questions or issues. Thanks again!

Link to comment
Share on other sites

Link to post
Share on other sites

import java.util.Random;import java.util.Scanner;public class HangMan{    private static int wordChoice;    private static String displayedWord;    public static String pickWord(int wordChoice)    {        switch(wordChoice)        {            case 0:            displayedWord = "motherboard";            break;            case 1:            displayedWord = "case";            break;            case 2:            displayedWord = "powersupply";            break;            case 3:            displayedWord = "harddrive";            break;            case 4:            displayedWord = "mouse";            break;            case 5:            displayedWord = "keyboard";            break;            case 6:            displayedWord = "peripheral";            break;            case 7:            displayedWord = "graphicscard";            break;            case 8:            displayedWord = "processor";            break;            case 9:            displayedWord = "latency";            break;            case 10:            displayedWord = "ping";            break;            case 11:            displayedWord = "gaming";            break;            case 12:            displayedWord = "resolution";            break;            case 13:            displayedWord = "watercooling";            break;            case 14:            displayedWord = "cache";            break;            case 15:            displayedWord = "memory";            break;            case 16:            displayedWord = "chipset";            break;            case 17:            displayedWord = "intel";            break;            case 18:            displayedWord = "notebook";            break;            case 19:            displayedWord = "desktop";            break;            case 20:            displayedWord = "aliasing";            break;        }        return displayedWord;    }    public static void main(String[]args)    {        Scanner scan = new Scanner(System.in);        String userChoice;        int gameCount = 0;        int lostGames = 0;        System.out.print("Welcome to a game of hangman!");        System.out.print("Do you want to play? (Y/N): ");        userChoice = scan.next();        while (!userChoice.equalsIgnoreCase("n"))        {            switch (userChoice)            {                case "Y":                case "y":                Random wordPick = new Random();                wordChoice = wordPick.nextInt(20);                pickWord(wordChoice);                letterReplacement(displayedWord);                break;                              default:                System.out.println("Bad input.");                break;            }            gameCount++;            System.out.println("You have played " + gameCount + " games. Do you want to play again?");            userChoice = scan.next();        }     }    public static void letterReplacement (String displayedWord)    {        Scanner scan = new Scanner(System.in);        int wordLength = displayedWord.length();        int numberOfLetters = 0;        StringBuilder guessingWord = new StringBuilder();        while(numberOfLetters < wordLength)        {            guessingWord.append(" _ ");            numberOfLetters++;        }        System.out.println(guessingWord);        char guessedLetter;        int guessesLeft = 6;        int letter;        System.out.print("Please guess a letter: ");                while(guessesLeft > -1)        {            guessedLetter = scan.next().charAt(0);            for(letter = 0; letter < displayedWord.length(); letter++)            {                if(displayedWord.charAt(letter) == guessedLetter)                {                    guessingWord.deleteCharAt(letter*3+1);                    guessingWord.insert(letter*3+1, guessedLetter);                    System.out.println(guessingWord);                }                            }            guessesLeft--;        }    }}

Can someone help me with this? I want the user to have a total of 6 wrong guesses. So essentially every time you guess a wrong letter, it displays that you have only 5,4,3 etc wrong guesses left. Also when I guess a letter, if it appears twice in the word, the word will print out twice, one with one of the letters in it, and the other with the other letter in it. So if the word is "peripheral" if you guess e, it would print out _ e _ _ _ _ _ etc. and then _ e _ _ _ _ e _ _ _.

Link to comment
Share on other sites

Link to post
Share on other sites

Can someone help me with this? I want the user to have a total of 6 wrong guesses. So essentially every time you guess a wrong letter, it displays that you have only 5,4,3 etc wrong guesses left. Also when I guess a letter, if it appears twice in the word, the word will print out twice, one with one of the letters in it, and the other with the other letter in it. So if the word is "peripheral" if you guess e, it would print out _ e _ _ _ _ _ etc. and then _ e _ _ _ _ e _ _ _.

 

To fix the printing issue, move System.out.println(guessingWord); out of the for loop so it only prints once after all the characters have been checked.

 

To keep track of the wrong guesses, use a boolean. Once the loop is done, you can check the boolean to see if you want to do something.

// Example 1 - assume true, try to prove falseboolean test = true;for (...) {    if (...) {        test = false;        // break; is optional if you want to stop the loop here    }}if (!test) {    // do something}// Example 2 - assume false, try to prove trueboolean test = false;for (...) {    if (...) {        test = true;        // break; is optional if you want to stop the loop here    }}if (test) {    // do something}
Link to comment
Share on other sites

Link to post
Share on other sites

Played around with the code here's what I got:

 

import java.util.*;public class HelloWorld {        private static String[] words = {        "motherboard", "case", "powersupply", "harddrive", "mouse", "keyboard", "peripheral",        "graphicscard", "processor", "latency", "ping", "gaming", "resolution", "watercooling",        "cache", "memory", "chipset", "intel", "notebook", "desktop", "aliasing" };            public static void main(String[] args) {        Random rand = new Random();        String userChoice =             readLine("Welcome to a game of hangman!\nDo you want to play? (Y/N): ");                int gameCount = 0;        int lostGames = 0;        while (!userChoice.equalsIgnoreCase("n")) {            switch(userChoice.toLowerCase()) {                case "y":                    String word = words[rand.nextInt(words.length)];                    if (!playGame(word, 6))                        lostGames++;                                        gameCount++;                    break;                default:                    System.out.println("Sorry, didn't understand that.");                    break;            }                        userChoice =                 readLine("You have played " + gameCount + " games. Do you want to play again?");        }                System.out.println("Thanks for playing");    }        private static Boolean playGame(String word, int guessesLeft)  {        String hiddenWord = initHiddenWord(word);        while(guessesLeft > 0)        {            String inChar = readLine("Your guess: ");            while(true) {                if (inChar.length() > 1)                    inChar = readLine("You can only guess one letter at a time");                if (inChar.length() == 1) break;            }            char ch = Character.toLowerCase(inChar.charAt(0));            if (!letterOk(word, ch))                guessesLeft--;            else                hiddenWord = replaceLetters(word, hiddenWord, ch);            if (hiddenWord.equals(word)) {                System.out.println("You guessed the word: " + word);                System.out.println("You win");                return true;            }            System.out.println("The word now looks like this: " + hiddenWord);            System.out.println("You have " + guessesLeft + " guesses left.");        }                return false;        }        private static String initHiddenWord(String word) {        String result = "";        for(int i = 0; i < word.length(); i++)            result = result + "-";        return result;    }        private static Boolean letterOk(String word, char guess) {        if (word.indexOf(guess) == -1) {            System.out.println("There are no " + guess + "'s in the word.");            return false;        } else {            System.out.println("Found " + guess + "'s in the word.");            return true;        }    }        private static String replaceLetters(String word, String hiddenWord, char guess) {        for(int i = 0; i < word.length(); i++) {            if (guess == word.charAt(i)) {                if (i > 0)                    hiddenWord = hiddenWord.substring(0, i) + guess +                        hiddenWord.substring(i + 1);                if (i == 0)                    hiddenWord = guess + hiddenWord.substring(1);            }        }        return hiddenWord;    }        static Scanner scan = new Scanner(System.in);    private static String readLine(String consoleOutput) {        System.out.println(consoleOutput);        return scan.next();    }}
Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×