1

ここに行きます。Java での割り当てに問題があります。ユーザーが欠落しているフレーズから文字を推測する必要があるプログラムを作成するように求められます。フレーズを作成し、各文字を ? に置き換えましたが、ユーザーは推測する必要があります。ユーザーが正しい場合に各文字を表示する for ループを作成するにはどうすればよいですか。これは私が日食でこれまで持っているものです。

    public static void main(String[]args)
 {
    Scanner stdIn = new Scanner(System.in);

    String cPhrase = "be understaning";
    char g;
    boolean found;
    String guessed;

    System.out.println("\tCommon Phrase");
    System.out.println("_ _ _ _ _ _ _ _ _ _ _ _ _");
    System.out.println(cPhrase.replaceAll("[a-z]", "?"));
    System.out.println(" ");
    System.out.print(" Enter a lowercase letter guess: ");

    g = stdIn.nextLine();  // I am trumped right  here not sure what to do?
                                      // Can't convert char to str
    for (int i = 0; i < cPhrase.length(); ++i)
    {
        if( cPhrase.charAt(i) == g)
            {
            found = true;
            }
        if (found)
        {
            guessed += g;
4

3 に答える 3

0

You're almost there.

Use a while instead of a for loop tied to a boolean condition. The boolean would be set to false if and only if all characters in word guessed.

于 2012-11-05T15:17:50.307 に答える
0

ここに簡単な解決策があります。ただし、コピーして貼り付けるだけでなく、理解する必要があります (そのため、インライン コメントを入れています)。

public static void main(String[] args)
{
    Scanner stdIn = new Scanner(System.in);

    String phrase = "be understanding";
    boolean[] guessed = new boolean[phrase.length()];
    // walk thru the phrase and set all non-chars to be guessed
    for (int i = 0; i < phrase.length(); i++)
        if (!phrase.substring(i, i + 1).matches("[a-z]"))
            guessed[i] = true;

    // loop until we break out
    while (true)
    {
        System.out.print("Please guess a char: ");
        char in = stdIn.nextLine().charAt(0);

        boolean allGuessed = true;
        System.out.print("Phrase: ");
        // walk over each char in the phrase
        for (int i = 0; i < phrase.length(); i++)
        {
            char c = phrase.charAt(i);
            // and check if he matches the input
            if (in == c)
                guessed[i] = true;
            // if we have an not already guessed char, dont end it
            if (!guessed[i])
                allGuessed = false;
            // print out the char if it is guessed (note the ternary if operator)
            System.out.print(guessed[i] ? c : "?");
        }
        System.out.println("\n------------------");
        // if all chars are guessed break out of the loop
        if (allGuessed)
            break;
    }

    System.out.println("Congrats, you solved the puzzle!");

    stdIn.close();
}
于 2012-11-05T15:39:52.223 に答える