在我的代碼結束時,用戶選擇重複。當它輸出整個循環與原來的工作,而不是一個新的輸入單詞。例如,如果用戶輸入單詞比薩。它會以我想要的方式完成循環。當我選擇重複它時,循環會再次使用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時,它會立即重複播放而不要求我提供新單詞。我怎樣才能得到想要的結果?
**你在哪裏**要求循環內的**字?我的意思是,你在哪裏可以找到下一個單詞?即'word = input.nextLine();'你是一個邏輯錯誤,你只需要遍歷你的代碼,通過邏輯思考就可以了。 – 2014-11-14 17:58:26
在做其他事情之前,您應該詢問輸入,然後根據輸入以某種方式進行。我認爲,因爲你在while循環結尾處要求輸入,所以它會混淆邏輯。 – 2014-11-14 18:03:18
這種縮進是不好的,它傷害了我的大腦。 – khelwood 2014-11-14 20:43:23