SavannahC123
SavannahC123

Reputation: 13

Converting a String to an array of characters

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

Upvotes: 0

Views: 2653

Answers (3)

CodeCamper
CodeCamper

Reputation: 6980

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!

Upvotes: -1

zaPlayer
zaPlayer

Reputation: 862

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;
}
}

Upvotes: 0

Rainbolt
Rainbolt

Reputation: 3660

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.

Upvotes: 2

Related Questions