Simple Java Hangman Assignment

后端 未结 5 2062
夕颜
夕颜 2021-02-06 06:05

I\'m stuck on a java assignment for a class where we need to make a Hangman game but a REALLY BASIC one (It\'s an intro to Java class). Basically I have a word entered by someon

5条回答
  •  忘掉有多难
    2021-02-06 06:24

    Hey Jordan, your first attempt looks very good! You only need some more logic inside the while loop to read guesses and replace "*"s with correct guesses. And I would advise you to store the obfuscated word ("*****...") in a string also instead of just printing it out, will be handy later on..

    Judging by your code you don't need any help on user input, your only problem is correct replacing of stars with right guesses, lets get to it:

    String secret;
    //read in secret string
    String displaySecret;
    //generate as many "*"s as secret is long and store them in displaySecret
    

    Now the cool thing is this:

    ...no repeated letters...

    which will make your assignment much easier! Look at the documentation of the String class provided by Williwaw. There you'll find two methods with which will lead to the solution:

    • One method finds the first occurrence of a character inside a string and outputs its position. And since you don't accept duplicate letters, that'll also be the only occurrence.
    • The other method can replace the character at a given position inside a string with another character.

    I think from that you'll find the solution easily. Feel free to ask further questions in the comments!

    EDIT: Some more help

    String secret = "example-text";
    String displaySecret = "";
    for (int i = 0; i < secret.length(); i++)
        displaySecret += "*";
    
    char guess;
    //read in a guess
    int position = secret.indexOf(guess);
    //now position contains the index of guess inside secret, or
    //-1 if the guess was wrong
    
    String newDisplaySecret = "";
    for (int i = 0; i < secret.length(); i++)
        if (i == position)
            newDisplaySecret += secret.charAt(i); //newly guessed character
        else
            newDisplaySecret += displaySecret.charAt(i); //old state
    
    displaySecret = new String(newDisplaySecret);
    

    Damn I was sure there was some kind of setCharAt(int) method.. the loop does the job.

提交回复
热议问题