0

So I am doing a lab for my into to java programming class. I am playing the game of hangman using the console on jedit. They are only allowed to guess one letter at a time. At the beginning, only asterisks are displayed to show the number of letters. For example if the word was elephant it would display *********. Once they guess the letter e, it will display e*e*****. I have created a method that returns an array of characters which is the asterisks based on the number of letters in the word. I can't figure out how to replace the asterisks with the correct letter. Please help!

 public static char[] asterisk(String x) {
    char[] word = new char[x.length()] ;
    for( int i=0; i< x.length(); i++) {
        word[i] = '*' ;

    }// end for loop
    return word ;
} // end asterisk method
4
  • 1
    There is String#toCharArray, you know... Commented Apr 15, 2014 at 19:44
  • @LuiggiMendoza I will be implementing this asterisk method in main which returns an array of characters. I want to replace the asterisks that this method returns with the correct letters. Commented Apr 15, 2014 at 19:48
  • So what you want/need is to show the characters that were guessed right in the String, right? Commented Apr 15, 2014 at 19:50
  • @SavannahC123 If you check my answer and paste it into your IDE I am sure you will find it will work exactly as you wanted. Feel free to comment on it if you want me to explain it further. Commented Apr 15, 2014 at 21:08

3 Answers 3

2

We declare two Strings. One is the word and the other starts off as a bunch of asterisks.

String word = "hello"; 
String obfuscatedWord = "";

for (int i = 0; i < word.length; i++)
    obfuscatedWord += "*"

We get a guess from the user. We pass in obfuscated word, because the user needs it to make a guess.

char guess = getGuessFromUser(obfuscatedWord);

We pass the word, the obfuscated word, and the guess to a function and get back a new String.

static String replaceWithGuess(String word, String obfuscatedWord, char guess) {
    // Pseudocode here. You solve the rest.
    for i = 0 to word length:
        if word[i] equals guess:
            replace obfuscatedWord[i] with guess
    return obfuscatedWord;
}

Now you just have to increment the number of guesses, determine if the user won or lost, etc.

Sign up to request clarification or add additional context in comments.

11 Comments

I am a bit confused with the line that gets a guess from the user char guess = getGuessFromUser(obfuscatedWord) ; getGuessFromUser isn't anything that has been declared.
@SavannahC123 You need to declare it. static String getGuessFromUser(String obfuscatedWord) { /*Your code goes here.*/ } Also, when you don't understand something, ask an actual question. Don't go running to your customer, coworker, boss, or family member with anything remotely like "I'm confused." or "I don't understand." Say something like, "Do I need to declare that function or is part of Java's standard library?" The response you get will be much more powerful, and I waste less time trying to read your mind and figure out what it is you actually need.
Hey, you really don't need to go responding to me that way. I am pretty sure people appreciate it more when you tell them that you are confused compared to not saying anything at all. I did say in my original question that I am in an intro to java programming class. This is something that I am not too familiar with, and I do get confused. Being rude behind a computer gets you nowhere. I have had professors that welcome you saying you are confused, even if you don't know what questions to ask, you are letting them know you would like help.
@SavannahC123 Check my answer below I think it is exactly what you want. Don't mind Rusher, StackOverflow is a site for very specific questions and very specific answers and even though your question or confusion may be valid you will usually only find backlash here because we are trained to flag almost any question that is "help me with my homework".
@SavannahC123 Will you please explain what part of my last comment was rude? Declarations such as "I am confused." may be acceptable in a classroom setting, but they don't fly in the real world. Understand why and what you are confused about, and then form an actual question. Will you just take a moment to forget how rude you think I am being and just accept that a clearly written question is more appropriate than a statement in situations where you want to receive a helpful response?
|
0
String answer="dodo";
char[] ans=new char[answer.lenth];
for(char a:ans)
{
a='*';
}


//take input from user and then do this
char[] q=answer.toCharArray();
for (int i=0;i<answer.lenth;i++)
{

if(q[i]==theinput)
{
ans[i]=theinput;
}
}

1 Comment

You don't really explain what you're showing here. A good answer will try to help the asker learn what he's doing wrong and how to correct it, not just dump code on him.
-1

You should create a separate Hangman class. I have added comments in the code for you to understand each part. Here is a summary of the idea behind it:

variables

  • unmasked - this is where we will store our word
  • masked - this is where we will store our masked*** version of the word
  • revealed - this will slowly transition from masked to unmasked per the user guesses

methods

  • Constructor - we will create all of our variables here incorperating a new version of your masking method
  • Guess - This is where we will compare the guessed letter with the unmasked variable
  • isOver- This is how we know to stop asking the user for guesses

The bulk of your question is essentially answered in the Guess method which I will briefly explain the logic which is performed as we loop through each character:

  1. if the letter is an * check if the letter was guessed

  2. if the guess is wrong then put an *

  3. if the letter has already been revealed then put that revealed letter (important step for continuity you might overlook)

===========Here is the code below commented===========

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
    Scanner input = new Scanner(System.in); //provides a way to ask for input
    Hangman t = new Hangman("pajama"); //see the Hangman class I created at the bottom
    System.out.println(t.masked); //returns the word "pajama" masked with *
    while (!t.isOver()) { //keep asking the user for a char until you reveal the whole word
        System.out.print("Guess a character: "); //asks the user to guess a character
        try { 
        System.out.println(t.Guess(input.nextLine().charAt(0))); //accepts first character typed
        } catch (Exception e) {
        }
    }
    System.out.println("Congradulations you won!"); //tell the user he won by revealing the word
    input.close(); //close the input
    }

    public static class Hangman { //this class will make your objective easier
    public final String unmasked, masked; //final means it cannot be edited after it is assigned
    private String revealing; //this will be the string we will slowly reveal based on guesses
    private StringBuilder temp = new StringBuilder(); //this allows us to build strings out of characters in an efficient manner

    public Hangman(String word) { //constructor takes in the word for the game
        unmasked = word; //save the word in a separate variable unmasked
        for (int i = 0; i < word.length(); i++) //loop the length of the word
        temp.append('*'); //generate a string only with * the length of the word
        masked = revealing = temp.toString();// set masked and revealing to the *** string
        temp.setLength(0); //reset our StringBuilder for later use
    }

    public String Guess(char g) { //this method allows the user to guess a character
        for (int i = 0; i < masked.length(); i++)//check each letter
        temp.append(revealing.charAt(i) == '*' ? unmasked.charAt(i) == g ? g //this is called a ternary operator (condition)?(if true):(if false) and it is a shorthand for if/else
            : '*'
            : revealing.charAt(i)); 
        revealing = temp.toString(); //this updates the variable revealing so we can keep track of last correct guesses
        temp.setLength(0); //reset our StringBuilder for future use
        return revealing; //return the *** string with all the previous guesses revealed
    }

    public Boolean isOver() { //this checks if there is any * left to reveal
        return !revealing.contains("*");
    }
    }
    }

There is still a lot more you can modify and add to this class but I wanted to make sure I mainly just covered your exact question of how to replace the * with the guessed letters. Hope it helps!

6 Comments

Thank you for your help. I am going to work right now, and when I get back I will try it out. :)
@SavannahC123 If it works for you remember to chose it as the answer.
-1 for dumping code without explanation - "copy and paste this" isn't going to help the OP
@Doorknob The OP said they wanted to replace the * in a Hangman game format. So I opened up Eclipse and tested it out. I said if the OP has anymore further questions I would gladly explain in my answer. I don't see what really needs to be explained here unless you don't know what a loop is. Will it make you feel better if I put docs.oracle.com/javase/tutorial/essential in my answer?
@CodeCamper By just dumping code on the OP, you're not teaching anything - you're just encouraging poor copy/paste coding practices and not helping the OP understand what the code does.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.