2016-11-13 52 views
2

我必須創建一個遊戲,提示用戶輸入起始餘額,然後下注。然後他們贏或輸,他們的餘額相應地增加或減少。我的問題是,如果玩家想要再次玩,我不知道如何讓程序記住最後的平衡,然後在while循環中重新開始。當提示用戶時,我的餘額保持原來的第一筆餘額。對不起,如果這是一個重複,但我找不到這樣的問題,我一直在尋找超過一個小時。提前致謝。如果循環重複,試圖保持新的結尾餘額

import static java.lang.Math.*; 
import java.util.Scanner; 
public class BetGame 
{ 
    public static void main(String [] args) 
    { 
     Scanner in = new Scanner(System.in); 

     int die1, die2; 

     boolean looping = true; 

     System.out.println("Please enter your starting balance in whole dollars:");   
     double balance = in.nextDouble(); 
     System.out.println("Your beginning balance is " + balance + ", good luck!!"); 
     int guess = 0; 
     double bet2 = 0; 
     double endingBalance = 0; 
     while(looping) { 
      while (guess < 3) {//to allow the user to do this only 3 times  
       System.out.println("Enter a valid bet:"); 
       double bet = in.nextDouble(); 
       if (bet >= balance || bet >= endingBalance){ 
        System.out.println("That is more than your balance."); 
       } 
       else if (bet < balance || bet < endingBalance) {     
        bet2 = 0 + bet; 
        break; 
       } 
       guess++; 
       if (guess == 3) { 
        looping = false; 
        System.out.println("You have entered three invalid bets in a row. Please leave the casino."); 
       } 
      }   

      die1 = RollDie(); 
      die2 = RollDie(); 
      int sum = die1 + die2; 

      if (2 <= sum && sum <= 6) {     
       System.out.println("The roll is " + die1 + " and " + die2 + " for a " + sum + " for a win!"); 
       endingBalance = balance + bet2; 
      } 
      else if (7 <= sum && sum <= 12) { 
       System.out.println("The roll is " + die1 + " and " + die2 + " for a " + sum + " for a lose!"); 
       endingBalance = balance - bet2; 
      } 
      System.out.println("Your balance is " + endingBalance); 
      System.out.println("Do you want to roll again?"); 
      String answer = in.next(); 
      if ((answer.equals("n")) || (answer.equals("N"))) { 
       looping = false; 
      } 
     } 
     System.out.println("Your balance is " + endingBalance + ". Better luck next time! Have a wonderful evening!"); 
    }    

    static int RollDie() 
    { 
     int min = 1; 
     int max = 6; 

     return myRandomInteger(min, max); 
    } 

    static int myRandomInteger(int min, int max) 
    { 
     double range = max - min + 1.0; 
     int randomNum = (int)(range * Math.random()) + min; 

     return randomNum; 
    } 

} 
+0

我沒有試圖欺騙。我自己寫完整個問題。我只想得到如何讓程序記住價值的指導。我不是在尋找一個簡單的出路。 – Roxanne

+0

通過將其存儲到一個變量,也許? –

回答

2

可以存儲在變量

平衡
double balance = in.nextDouble(); 
    double originalBalance = balance; 
1

看看在這部分代碼:

if (bet >= balance || bet >= endingBalance){ 
       System.out.println("That is more than your balance."); 
} 

bet將始終大於endingBalance因爲endingBalance爲0