Simple Java Hangman Assignment

后端 未结 5 1986
夕颜
夕颜 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:19

    How to create HangMan Game

    package arr_game;

    import java.util.Random;
    import java.util.Scanner;
    public class HangMan3 {
        public static char[] star;
            public static void main (String args[])
            {   
                char game[];
                Scanner input = new Scanner(System.in);
                Random r = new Random();
                String[] arr = { "pakistan", "india", "jarmany", "america", "rashia", "iran", "iraq", "japan", "sudan", "canada"};
    
                String word = arr[r.nextInt(arr.length)];
                int count = word.length();
                char[] CharArr=word.toCharArray(); 
                char[] star = word.toCharArray();
            for(int i=0;i<star.length;i++)
            {
                star[i] = '*';
                System.out.print(star[i]);
            }
    
            for (int i=1; i<=3; i++)
            {
                System.out.printf ("\nGuess a Letter:");
                char letter= input.next().charAt(0);
    
                for (int j=0;j<CharArr.length; j++)
                {
                    if(letter == star[j])
                    {
                        System.out.println("this word already exist");
                    }
                    else
            {
                        if(letter==CharArr[j])
                        {
                            star[j]=letter;
                            i--;
                            System.out.printf("CORRECT GUESS!\n");
                        }
                    }
                }
                System.out.print(star);
                switch(i+0)
                {
                        case 1: System.err.printf("Strike 1\n");
                            break;
                        case 2: System.err.printf("Strike 2\n");
                            break;
                        case 3: System.err.printf("Strike 3\n");
                            System.err.printf("You're out!!! The word is Not_Matched\n");
                            break;
                }   
    
                System.out.printf("\n");
                if((new String(word)).equals(new String(star))) 
                {
                    System.err.printf("Winner Winner, Chicken Dinner!\n");
                    break;
                }
            }
        }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-06 06:26

    I'll give you a basic idea of the code upon which you can build:

    public class HangMan {
    public static void main(String[] args) {
        System.out.println("Enter Secrect Word");
        Scanner scn=new Scanner(System.in);
        String secrectStr = scn.next();
        StringBuilder b=new StringBuilder(secrectStr.length());
        for(int i=0;i<secrectStr.length();i++)
            b.append("*");
        char[] secrectStrCharArr=secrectStr.toCharArray(); 
        int charCnt=secrectStr.length();
        while(charCnt>=0){
            System.out.println("Secrect Word :"+b.toString());
            System.out.println("Guess a letter :");
            char guessChar = scn.next().toCharArray()[0];
            for(int i=0;i<secrectStrCharArr.length;i++){
                if(guessChar==secrectStrCharArr[i])
                    b.setCharAt(i,guessChar);
            }
        }
    
    }
    }
    
    0 讨论(0)
  • 2021-02-06 06:32

    It's not so stupid, the aim is to make you more able to come up with original solutions.
    Here, for example, you are working with Strings, so it would make sense to go on the javadoc and see the String page, to see if any function could come handy.
    Next, comes the logic : you get a "String" input, then only get "char"s input and you have to compare a String with a char. So, the best way is to compare each "char" of your "String".
    You can't use arrays ? Ok then, you can also use loops and two certain String functions (you already knows length(), which is one of the two), which will give the same result as going through a array to test each of its element.
    The game end if no * is displayed or if there is no attempts left, so the player can try as long as neither of those conditions are true.

    0 讨论(0)
  • 2021-02-06 06:34

    Store a array of characters that is the same length as the secret word. Initialize the characters to * and when a match is found, using [indexOf][1], reveal the found characters:

    String secretWord = userInput.next();
    int len = secretWord.length(); //Store the length which will be used to see if puzzle was solved.
    char[] temp = new char[len]; //Store a temp array which will be displayed to the user
    for(int i = 0; i < temp.length; i++) //initialize the array
    {
        temp[i] = '*';
    }
    System.out.print("\n");
    System.out.print("Word to date: ");
    while (attempts <= 10 && attempts > 0)
    {
        System.out.println("\nAttempts left: " + attempts);
        System.out.print("Enter letter: ");
        String test = userInput.next();
    
        if(test.length() != 1) 
        {
            System.out.println("Please enter 1 character");
            continue;
        }
    
        char testChar = test.charAt(0);
    
        //Find matches
        int foundPos = -2;
        int foundCount = 0; //How many matches did we find
        while((foundPos = secretWord.indexOf(testChar, foundPos + 1)) != -1)
        {
            temp[foundPos] = testChar; //Update the temp array from * to the correct character
            foundCount++;
            len--; //Decrease overall counter
        }
    
        if(foundCount == 0)
        {
            System.out.println("Sorry, didn't find any matches for " + test);
        }
        else
        {
            System.out.println("Found " + foundCount + " matches for " + test);
        }
    
        //Print 
        for(int i = 0; i < temp.length; i++)
        {
            System.out.print(temp[i]);
        }
        System.out.println();
    
        if(len == 0)
        {
            break; //Solved!
        }
    
        attempts--;
    }
    
    if(len == 0)
    {
        System.out.println("\n---------------------------");
        System.out.println("Solved!");
    }
    else
    {
        System.out.println("\n---------------------------");
        System.out.println("Sorry you didn't find the mystery word!");
        System.out.println("It was \"" + secretWord + "\"");
    }
    
    0 讨论(0)
提交回复
热议问题