如何停止为子手消除正确猜测的循环?

时间:2019-03-31 23:12:11

标签: java

以下是海绵一词的hang子手问题。 当用户输入正确的字符(s,p,o,n,g,e)时,hidden []数组将正确更新(将_替换为正确的字符)。

但是,当用户输入不正确的字符时,它将显示hidden [],其中包含所有_ _ _ _ _ _

任何提示都值得赞赏!谢谢

package javaapplication3;

import java.util.Scanner;

public class JavaApplication3 {

    public static void main(String[] args) {

        String secretWord = "sponge";
        int lettersLeft = secretWord.length();
        int attempts = 6;
        int position = 0; //Index of found character in string
        char[] hidden = new char[secretWord.length()]; //Array of hidden chars

        //Display initial hidden array
        for(int i=0; i < secretWord.length(); i++)
        {
            hidden[i] = '_';
            System.out.print(hidden[i] + " ");
        }

        do{
            System.out.println("");
            System.out.println("Attempts left = " + attempts);
            System.out.println("Enter a letter to guess the word: ");

            //User enters character
            Scanner scan2 = new Scanner (System.in);
            char test = scan2.next().charAt(0);

            //Search string secretWord if char test is in it
            if(secretWord.contains(Character.toString(test)))
            {
                position = secretWord.indexOf(test) +1;
                //System.out.println("Letter is in position: " + position);
                lettersLeft--;
            }
            else
            {
                position = 0;
                attempts--;
            }

            //Update hidden array with _ or correct char
            for(int i=0; i < secretWord.length(); i++)
            {
                if (position == 0)
                {
                    hidden[i] = '_';
                }
                else if (position != 0)
                {
                    hidden[position-1] = test;
                }
                System.out.print(hidden[i] + " ");
            }
        } while(lettersLeft != 0 && attempts != 0);

        if(attempts == 0)
        {
            System.out.println("You lost! The correct word was: " + secretWord);
        }

        if(lettersLeft == 0)
        {
            System.out.println("Good job! You won!");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果输入不正确,则用hidden重写整个_数组-在显示其内容的同一循环中。我不知道你为什么这么做。

您要做的只是更新hidden中的正确猜测,并保留不正确猜测的情况。

例如替换为:

//Update hidden array with _ or correct char
for(int i=0; i < secretWord.length(); i++)
{
    if (position == 0)
    {
    hidden[i] = '_';
    }
    else if (position != 0)
    {
       hidden[position-1] = test;     
    }
    System.out.print(hidden[i] + " ");
}

与此:

if (position != 0) {
    hidden[position - 1] = test;
}
for (int i = 0; i < secretWord.length(); i++) {
    System.out.print(hidden[i] + " ");
}