2012-11-05 77 views
1

這裏。我在Java中的任務遇到問題。我們被要求創建一個程序,用戶需要猜測缺失短語的字母。我創建了這個短語並用?替換了每個字符,但現在用戶需要猜測。如果用戶是正確的,我如何構造for循環來顯示每個字符。這是我迄今爲止在月食上所做的。Java編程做循環和庫

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; 
+0

這不是[tag:eclipse]問題。 –

+2

您的代碼示例不完整 - 大括號未被封閉。據推測你至少有一些東西可以編譯? –

+0

請發佈完整的[SSCCE](http://sscce.org/)(這是完整的可運行代碼)。並且在將代碼發佈到此處之前對代碼進行格式化(在Eclipse中,只需按Ctrl + Shift + F並選擇所有內容)。很好地說,否則的問題。 +1(一旦我再次獲得選票,即將發佈:D) – brimborium

回答

0

你快到了。

使用一段時間而不是綁定到布爾條件的for循環。當且僅當字中的所有字符都被猜出時,布爾值纔會被設置爲false。

+1

for循環用於檢查短語中是否包含字符,而不是循環猜測。 – Rouby

+0

@Rouby好抓!是。一段時間可能會包裝現有的impl。 –

0

你可以簡單地獲得輸入行的第一個字符(假定一個應該只是猜測一個字符在一個時間)

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

循環,直到用戶已經猜到了整個短語,你需要圍繞代碼爲while

while(not complete) 
{ 
    get input 
    process input 
    show progress 
} 
+0

並且不要忘記初始化變量'布爾發現'和'字符串猜測' –

+0

非常感謝。這非常有幫助。 –

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(); 
}