2014-11-14 76 views
-1

在我的代碼結束時,用戶選擇重複。當它輸出整個循環與原來的工作,而不是一個新的輸入單詞。例如,如果用戶輸入單詞比薩。它會以我想要的方式完成循環。當我選擇重複它時,循環會再次使用Pizza這個詞,而不是要求我另外輸入一個詞。我的代碼以我不想要的方式重複

do { 
if (answer == 1){ 
    System.out.println("Please enter another word:"); 
} 
    for (int i = 0; i < word.length(); i++) { 
    firstLetter = word.charAt(0); 
    word = word.substring(1, word.length()); 
    System.out.println(firstLetter + word); 
    word += firstLetter; 

} 
System.out.println("Would you like to Enter another word? If so, press 1. If not press 2."); 
answer = input.nextInt(); 
input.nextLine(); 
} 
    while(answer == 1); 
    System.out.println("Have a nice day!"); 
} 
} 

輸出這個代碼是: 比薩餅 izzap zzapi zapiz apizz 你想輸入一個字?如果是,請按1.如果不是,請按2. 當我按1時,它會立即重複播放而不要求我提供新單詞。我怎樣才能得到想要的結果?

+1

**你在哪裏**要求循環內的**字?我的意思是,你在哪裏可以找到下一個單詞?即'word = input.nextLine();'你是一個邏輯錯誤,你只需要遍歷你的代碼,通過邏輯思考就可以了。 – 2014-11-14 17:58:26

+0

在做其他事情之前,您應該詢問輸入,然後根據輸入以某種方式進行。我認爲,因爲你在while循環結尾處要求輸入,所以它會混淆邏輯。 – 2014-11-14 18:03:18

+0

這種縮進是不好的,它傷害了我的大腦。 – khelwood 2014-11-14 20:43:23

回答

2
System.out.println("Would you like to Enter another word? If so, press 1. If not press 2."); 
answer = input.nextInt(); 
input.nextLine(); 

我想如果你把最後一行將正常工作

更新

+0

@HovercraftFullOfEels tx,完成 – ControlAltDel 2014-11-17 15:30:04

1

也許是這樣吧。你也錯過了這個詞的輸入。你需要用戶的單詞和動作。

do { 
    System.out.println("1 for new word, 2 for exit"); 
    answer = input.nextInt(); 
    input.nextLine(); 
    System.out.println("input word"); 
    String word = input.nextLine(); 

    if (answer == 1){ 
     for (int i = 0; i < word.length(); i++) { 
      firstLetter = word.charAt(0); 
      word = word.substring(1, word.length()); 
      System.out.println(firstLetter + word); 
      word += firstLetter; 
     } 
    } 
} while(answer == 1); 
System.out.println("Have a nice day!"); 
+0

+1這是解決方案。該代碼需要對'input.nextLine()'進行兩次調用,一次只需吞服EOL,另一次調用下一個單詞並將其放入'word'變量中。 – 2014-11-14 20:49:37

相關問題