Simple Java Hangman Assignment

后端 未结 5 1987
夕颜
夕颜 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: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 + "\"");
    }
    

提交回复
热议问题