2013-01-06 23 views
-3

我想寫一段代碼,讓我鍵入一個字母,然後檢查該字母是否屬於該字。然後它應該只顯示正確的字母可見的單詞。猜字(例如:**** *******)

例子:

字,我需要猜測:叢林書

的屏幕上顯示:***** ****

信,我猜測:J-

在屏幕上顯示:j**** ****

等等

到目前爲止,我已經得到了什麼:

public void guessConsonent() { 
    String guessedConsonent = consonentInput(); 
    // returns a letter 

    wordInStars = ""; 

    for (int s = 0; s < secretWord.length(); s++) 
     if (secretWord.substring(s, s+1).equals(guessedConsonent)) { 
      wordInStars += guessedConsonent; 
     } else if (woordVanCat.substring(s, s+1).equals(" ")) { 
      wordInStars += " "; 
     } else { 
      wordInStars += "*"; 
     } 
    System.out.println(wordInStars); 
} 

的問題是,它不consonent增加,即使它是正確的字。我仍然只能得到 ' * **'

問候

+7

是什麼在這裏你的問題 – Jayamohan

+0

它不工作,它不會第j添加到單詞 – Jente

+0

1)爲了更好地幫助越早,張貼[SSCCE](HTTP ://sscce.org/)。 2)鑑於變量名稱是描述性的,並且您在以英語進行的論壇上尋求幫助,請使用基於英文的屬性名稱。 –

回答

3

看來你正在編寫一個hangman-clone in Java。我沒有看到的片段是:

if (wordVanCat.charAt(i) == a){ 
    woordSterRaden.setCharAt(i, a); 
} else { 
    woordSterRaden.setCharAt(i, '*'); 
} 
+0

它實際上是一個財富遊戲輪。有了這段代碼,我應該改變一下我猜測的這個組合嗎?如果有空間呢?我不想要一個空間成爲*。在此先感謝 – Jente

+0

爲字母添加正則表達式檢查,如new String(a).lowerCase()。matches(「^ [a-z] +」); – hd1

0
void guess() { 
    Scanner cin = new Scanner(System.in); 
    String yes = "Hello World"; 
    String g = ""; 
    for (int i = 0; i < yes.length(); ++i) g += '*'; 
    while (!yes.equals(g)) { 
     String resp = cin.next(); 
     String temp = ""; 
     for (int i = 0; i < yes.length(); ++i) { 
      if (g.charAt(i) == '*' && yes.charAt(i) == resp.charAt(0)) 
       temp += resp.charAt(0); 
      else 
       temp += g.charAt(i); 
     } 
     g = temp; 
    } 
}