Hangman计划需要建议

时间:2016-05-08 21:31:29

标签: java

我是新来的java编程新手,我需要帮助一个我必须为11年级com sci创建的刽子手游戏。我必须为随机生成的单词创建短划线,并用用户输入的字母替换正确的单词。我可以替换破折号没有问题,只是因为它在for循环中我无法保持它。这就是我得到的:

'for(int e = 0; e < rndword.length; e++)
  {
    if(rndword[e] == guess.charAt(0))
    {
      System.out.print(guess);
    }
    else if(rndword[e] == ' ')
    {
     System.out.print(" ");
    }
    else
    {
     System.out.print("-");
    }


  }`

示例输出将是:

字:佳能

输入一封信:“o”

- O -

输入一封信:“c”

ç----

之前输入的信件不会再出现。

提前致谢!

(P.S。我对java很新,所以我所知道的是数组,switch,for / while循环,并且while while循环)

2 个答案:

答案 0 :(得分:1)

更好的方法是存储两个数组,一个用于向用户显示的内容,另一个用于真实单词。

然后,当用户获得正确的字母时,您可以修改显示给用户的数组。

类似的东西:

char[] rndword; //put the word they are trying to guess here
char[] display; //show this one to the user (start by populating it with dashes and / or spaces)

for(int e = 0; e < rndword.length; e++) {
    if(rndword[e] == guess.charAt(0))
    {
        display[e] = guess.charAt(0);
    }
    System.out.print(display[e]);
}
System.out.println();

所以display会像“---- - ----”一样开始,但如果用户猜到'A'并且它有一个'A',那么它将被改为“ - A- - -AA“然后打印出来。

答案 1 :(得分:0)

快速实施我的评论:

String randomWord;
char[] display;
char guess;

void nextGame(){
    randomWord = <whatever you do here>;
    word = new char[randomWord.length()];
}

for(int e = 0; e < randomWord.length; e++) {
    if(randomWord[e] == guess)
       display[e] = guess;
}

void checkWon() {
    for(char c : display) 
       if(c == '-'){
          System.out.print(display); return;
       }

    System.out.println("Won message.");
}
相关问题