我和我的同学,目前正在学习Java,这是我们的第一个项目。我们必须制作一个骰子游戏,你可以在滚动后获得2个骰子的总和,你必须猜测每个骰子的眼睛。如果他们失败了,他们就会失去他们已经下注的信用额度,并且他们可以选择重新开始,并说出" y"是的,和" n"不。如果他们说是,则假设游戏重启,并保留他们当前的信用。我们如何重新启动游戏并保持当前的信用值?
package dicegame_v1;
import java.util.Scanner;
/**
*
* @author williampfaffe
*/
public class Game_engine {
Player playerTest = new Player();
int start_credit = 100;
private static final Scanner s = new Scanner(System.in);
public Game_engine() {
/////////////////////////////////////// VI MANGLER TERNINGERNES UDFALD
String playerName = playerTest.getName();
System.out.println("Hi, " + playerName + "! Your current balance is " + start_credit + " credit. Please place your bet here:");
int input = s.nextInt();
start_credit = start_credit - input;
if (input > 100) {
System.out.println("The amount of money you have tried to bet, "
+ "is larger than your current balance. You only have:" + start_credit
+ " left on your account");
} else {
Dice diceRoll1 = new Dice();
diceRoll1.rollDice1();
diceRoll1.getDice1();
diceRoll1.getDice2();
System.out.println("The total sum is: " + diceRoll1.diceSum());
System.out.println("First guess: ");
int input_dice1 = s.nextInt();
System.out.println("Second guess: ");
int input_dice2 = s.nextInt();
if (input_dice1 == diceRoll1.getDice1() && input_dice2 == diceRoll1.getDice2()) {
start_credit = (input * 2) + start_credit;
System.out.println("You're correct! You have won: " + input + ". Your current balance is now: " + (start_credit));
System.out.println("Do you want to continue playing? Yes: y No: n");
String keep_playing = s.nextLine();
if (keep_playing.equals("y")) {
System.out.println("");
} else {
System.out.println("Hope to see you again!");
}
} else {
System.out.println("You're incorrect! You have lost your money! Your current balance is: " + (start_credit));
System.out.println("Do you want to continue playing? Yes: y No: n");
String keep_playing = s.nextLine();
if (keep_playing.equals("n")) {
System.out.println("Hope to see you again!");
} else {
System.out.println("");
}
}
}
}
}

答案 0 :(得分:1)
将if / else包装在一个循环中,如:
while (true) {
...
if (keep_playing.equals("y")) {//you may want to use equalsIgnoreCase api to do case insensitive match for y ?
continue;
} else {
System.out.println("Hope to see you again!");
break;
}
}
答案 1 :(得分:0)
您将其封装在while
循环中,该循环检查转义条件:
boolean game = true;
while(game) {
//Do your stuff
if(keep_playing.equals("n")) {
game = false;
}
}