2017-01-01 16 views
0

我想讓它每次調用hiddenWord();時都顯示一個單詞提示,取決於所嘗試的猜測字母,所以沒有猜測,你會得到這樣的"____",如果這個詞是例如邁克和我猜'我'和'e'它會顯示"_i_e"。 我已經在這裏呆了很長一段時間,我無法用頭裹着它。如果問題是非常基本的,我仍然是一個很抱歉的新手。試圖製作一種顯示遊戲猜測字母的方法Hang Man(Java)

我會發布我試圖做的方法,而無需程序的其餘部分,如果需要我可以發佈其餘的。這種方法有兩個主要問題。

1-我需要​​至少有3個字符,所以在它的當前狀態是「」它不起作用。這就是爲什麼在下面添加3個空格。否則我會得到一個我不明白的索引錯誤。

2-第二個問題是如何正確分配"_"當我沒有找到這封信時,我似乎在做太多破折號。

public String hiddenWord() { 
     int i = 1; 
     int j = 1; 
     this.guessedLetters += " "; 
     char c = this.word.charAt(i); 
     char d = this.guessedLetters.charAt(j); 
     while (i <= this.guessedLetters.length()-1) { 
      while (j <= this.word.length()-1) { 
       if (c == d) { 
        this.hiddenWord += c; 
        j++; 
       } 
       else { 
        this.hiddenWord += "_"; 
        j++; 
       }    
      } 
      i++; 
     } 
     return this.hiddenWord; 
    } 
} 
+0

1.指數應該從0開始,而不是1 2.您需要復位j對於i的每個迭代上面的類的一個使用例。 3.當我改變時,需要查找c,並且當j改變時,也需要d。他們只會受到分配時i和j值的影響。 4.你應該迭代外循環中的單詞長度和內循環中的猜測字母。 5.您可能可以使用STring replace()或replaceAll()函數找到替代解決方案 – samgak

+0

用戶每次只能猜測一個字母? – Dummy

+0

是的。一次只有一封信。 – Budaika

回答

0

我爲你整理了一堂課。我根據我可以從你的描述中推斷出來寫它。

public class Hangman { 
    // This char array will hold the result after each guess 
    // for example, if the word is "mike", and the use guesses 'i' 
    // the result array will contain ['_', 'i', '_', '_'] 
    private char[] result = null; 

    // The word the user has to guess 
    private String word = null; 

    public Hangman(String word) { 
     this.word = word; 
     result = new char[word.length()]; 
     // initialize the result to contain only underscores 
     for (int i = 0; i < result.length; i++) 
      result[i] = '_'; 
    } 

    public String getResult(char guessChar) { 
     // The underlying char array of the secret word 
     char[] wordArray = word.toCharArray(); 
     for (int i = 0; i < wordArray.length; i++) { 
      if (wordArray[i] == guessChar) 
       result[i] = guessChar; 
     } 
     return new String(result); 
    } 
} 

這裏是

public class Test { 
    public static void main(String[] args) { 
     Hangman h = new Hangman("mike"); 
     System.out.println(h.getResult('i')); // prints _i__ 
     System.out.println(h.getResult('e')); // prints _i_e 

    } 
}