Reputation: 325
Me and my classmate, is currently in progress of learning Java, and this is our first project. We have to make a dice game, where you get the sum of 2 dices after a roll, where you have to guess the eyes of each dice. If they lose, they lose the amount of credit that they have betted, and they get a option to start over, by saying "y" for yes, and "n" for no. If they say yes, the game is suppose to restart, and keep their current credit. How do we restart the game, and keep the current credit value?
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("");
}
}
}
}
}
Upvotes: 0
Views: 459
Reputation: 37023
Just wrap your if/else within a loop like:
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;
}
}
Upvotes: 1
Reputation: 840
You encapsulate it in a while
- loop, which checks for an escape condition:
boolean game = true;
while(game) {
//Do your stuff
if(keep_playing.equals("n")) {
game = false;
}
}
Upvotes: 0