1

开始。我在 Java 中分配作业时遇到问题。我们被要求创建一个程序,用户需要从丢失的短语中猜测字母。我创建了这个短语并用 ? 替换了每个字符,但现在用户需要猜测。如果用户正确,我如何构造 for 循环以显示每个字符。这就是我迄今为止在 Eclipse 上所拥有的。

    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

这是一个快速的解决方案。但是请不要只是复制粘贴,您仍然需要理解它(因此我放入了内联评论)。

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 回答
0

您快到了。

使用 while 而不是绑定到布尔条件的 for 循环。当且仅当 word 中的所有字符都猜到时,布尔值才会设置为 false。

于 2012-11-05T15:17:50.307 回答
0

您可以简单地获取输入行的第一个字符(假设一次只猜测一个字符)

g = stdIn.nextLine().charAt(0);

要循环直到用户猜出整个短语,您需要用 . 将代码括起来while

while(not complete)
{
  get input
  process input
  show progress
}
于 2012-11-05T15:19:46.447 回答