2015-11-19 52 views
0

如何在不同的類中使用我的main中的數組。我正在製作一款遊戲,我需要一次擲骰三次。然後我拿出每個值並進行比較,比如2/3的數字匹配。如果再添加到12則給玩家回鍋。 這是我想使用數組中的信息的類。我昨天晚上了解了陣列和循環,所以我真的不知道我在做什麼在java中的2個獨立的類中使用數組

import java.util.Scanner; 

public class Game { 

private double Bet; 
private double Pot; 
private double TotalPot; 

public void Pot(){ 
Pot = 50; 
} 
public void inputBet() { 
    Scanner keyboard = new Scanner (System.in); 
    System.out.println("Please enter the current month in numerical format: "); 
    Bet = keyboard.nextDouble(); 
    if (Bet <= Pot) { 
     System.out.println("Error, Bet out of range"); 

     inputBet(); 
    } 
    else if (Bet == 0) { 
     System.out.println("Thank you for playing"); 
    } 
} 

public void inputEnd(){ 

} 

public void removeBet(){ 
    TotalPot = Bet - Pot; 
} 
public void dieComparison1(){ 
if ((die[0] == die[1]) || (die[0] == die[2])){ 
    TotalPot = (Bet * 2) + Pot; 
    } 
} 
public void print(){ 
System.out.println(+ TotalPot);} 
} 

這是我的主要創建數組的地方。

public class Assign3 { 

public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    //Game smith = new Game(); 
    //smith.Pot(); 
    //smith.inputBet(); 
    int[] die = new int[3]; 
    Die bob = new Die(); 
    int total = 0; 
    for(int i = 0; i < 3; i++){ 
     die[i] = bob.rollDie(); 
     bob.displayDie(die[i]); 
     total = total + die[i]; 
    } 
    bob.displayDie(total); 


} 
} 
+2

你的問題不清楚:從主'()'你調用的方法,如'rollDie()'和' displayDie()'但你不會向我們展示他們的實現。此外,你不解釋你想要達到什麼目的,數組的作用是什麼等等。 – alfasin

+0

你的'inputBet'方法要求用戶*「請用數字格式輸入當前月份:」 *但投入需要投注。你是否從某處複製了代碼並試圖修改它以實現程序的預期結果? – Blip

+0

如果你想以某種方式將die數組放入Game類中,那很簡單。嘗試這樣的: '遊戲遊戲=新遊戲(死);' 遊戲構造函數看起來像這樣: 'public Game(int [] dieArray){}' 有意義嗎? –

回答

0

在您發佈您在main方法您都談到了,你創造了Game類的一個實例行以上代碼:

//Game smith = new Game(); 
//smith.Pot(); 
//smith.inputBet(); 

如你首先創建的Game實例並將其存儲在變量smith中,然後在smith變量上調用方法PotinputBet方法,則可以在Game類中聲明另一種方法,如rollDie包含用於滾動模具的代碼,並將其從main方法中調用爲smith.rollDie()。這將消除您在main中創建的陣列die需要從Game類訪問的要求。

我的意思上面說的是:在你的Game

  1. 首先你創建int[]類型的變量die並初始化一個大小爲3的爲:

    private int[] die = new int[3]; 
    
  2. 你裝箱方法說rollDie()方法包含滾動模具的方法爲:

    public void rollDie(){ 
        Die bob = new Die(); 
        int total = 0; 
        for(int i = 0; i < 3; i++){ 
         die[i] = bob.rollDie(); 
         bob.displayDie(die[i]); 
         total = total + die[i]; 
        } 
        bob.displayDie(total); 
    } 
    
  3. 現在在您的main方法評論中,所有未被評論的評論和取消評論所有評論。然後添加一行smith.rollDie()推出芯片和得到的結果爲:

    Game smith = new Game(); 
    smith.Pot(); 
    smith.inputBet(); 
    smith.rollDie(); 
    // Here call the other method that are required to play the game like `dieComparision1()` etc. 
    /*int[] die = new int[3]; 
    Die bob = new Die(); 
    int total = 0; 
    for(int i = 0; i < 3; i++){ 
        die[i] = bob.rollDie(); 
        bob.displayDie(die[i]); 
        total = total + die[i]; 
    } 
    bob.displayDie(total);*/ 
    
相關問題