我正在制作一个Hangman的迷你小游戏。用户有10次猜测的机会,但只有5次生命。
该应用程序可以运行,但会在第5次生命之后继续,即使我希望它会让玩家退出该循环。
可实例化的类(Hangman.java)正常运行。
秘密词是“julie”,如可实例化的类中所述。
我的App类:
import javax.swing.JOptionPane;
public class HangmanApp {
public static void main(String args[]) {
String input, secret, result, playAgain;
char guess;
int i, j, k, lives;
Hangman myHangman = new Hangman();
do{
JOptionPane.showMessageDialog(null, "Hello, welcome to Hangman! You have 10 chances but only 5 lives! Best of luck");
lives = 5;
for (j = 10; j > 0; j--) {
while (lives >= 0){
input = JOptionPane.showInputDialog(null, "Please enter a letter");
guess = input.charAt(0);
//process
myHangman.setGuess(guess);
myHangman.compute();
result = myHangman.getResult();
if ((input.charAt(0) == 'j') || (input.charAt(0) == 'u') || (input.charAt(0) == 'l') || (input.charAt(0) == 'i') || (input.charAt(0) == 'e')) {
JOptionPane.showMessageDialog(null, "That letter is in the word! Current correct letters: " + result + ".");
} else {
lives--;
JOptionPane.showMessageDialog(null, "Sorry, that letter is not there. Current correct letters: " + result + ".");
}
//output
//JOptionPane.showMessageDialog(null, "Current correct letters: " + result);
};
lives = -1;
}
result = myHangman.getResult();
secret = myHangman.getSecret();
if (secret.equals(result)) {
JOptionPane.showMessageDialog(null, "Congratulations, you got it!! The word was " + secret + ".");
} else {
JOptionPane.showMessageDialog(null, "Sorry, you didn't get it, better look next time! The word was " + secret + ".");
}
playAgain = JOptionPane.showInputDialog("Do you want to play again? yes/no");
}while (playAgain.equals("yes"));
}
}
答案 0 :(得分:3)
请尝试以下更改:
while (lives > 0){
你从5开始,然后下降到4 3 2 1和0.随着改变,这将停止在0
答案 1 :(得分:0)
// don't need two nested cycles, you can do it in a single one
// The cycle exits if any one of the conditions fail
// max attempts exhausted or all the lives are lost
// -------------------v v------------------------
for (j = 10, lives=5; j > 0 && lives > 0 ; j--) {
// -------------------------------------^
// j - the number of attempt is decremented for each trial,
// no matter if successful or not
//... the rest of cycle logic, which will decrement the lives
// only in cases of unsuccessful attempts
}