2016-05-21 62 views
0

我想在Java中做一個基本的「交易或不交易」遊戲。我遇到了添加和刪除多維數組列表的問題。 問題發生在shuffleBoxes()的第7行和playerBox()的第9行。交易或沒有交易遊戲Java ArrayList問題

package Deal; 

import java.util.*; 
import java.io.*; 
import javax.swing.*; 

public class sample { 
    public static ArrayList <ArrayList<Integer>> boxes = new ArrayList<ArrayList<Integer>>(22); 

    public static void main (String [] args) throws IOException { 
     playerBox(); 
     dealerOffer(); 
    } 

    public static void shuffleBoxes() { 
     int [] prizes = {1,2,3,4,5,6,10,50,100,250,500,750,1000,3000,10000,15000,20000,35000,50000,75000,100000,250000}; 
     for (int i = 0; i < boxes.size(); i++) { 
      boxes.get(i).add(i+1); 
     } 
     for (int j = 0; j < boxes.size(); j++) { 
      boxes.get(j).get(1).add(prizes[j]); 
     } 
     Collections.shuffle(boxes); 
    } 

    public static int playerBox() { 
     String[] boxChoice = {"1", "2", "3", "4", "5", "6", "7", "8", "9" ,"10", "11", "12", "13", 
     "14", "15", "16", "17", "18", "19", "20", "21", "22"}; 
     String input = (String)JOptionPane.showInputDialog(null, "Choose a box...", "Choose carefully", 
     JOptionPane.QUESTION_MESSAGE, null, boxChoice, boxChoice[0]); 
     int chosenBox = Integer.parseInt(input); 
     for (int i = 0; i < boxes.size(); i++) { 
      if (chosenBox == boxes.get(i).get(0)) 
       boxes.get(i).get(0).remove(chosenBox); 
     } 
     return chosenBox; 
    } 

    public static void dealerOffer() { 
     int average; 
     int sum = 0; 
     for (int i = 0; i < boxes.size(); i++) { 
      sum = sum + (boxes.get(i).get(1)); 
     } 
     average = sum/boxes.size(); 
    } 
} 
+2

那麼你想要什麼? –

+2

'我遇到了添加和刪除多維數據列表的問題。'如果解釋什麼是問題,這將是很好的。什麼錯誤?你在期待什麼? –

回答

3

創建

ArrayList <ArrayList<Integer>> boxes = new ArrayList<ArrayList<Integer>>(22); 

但這不把任何東西到ArrayList。我在代碼中看不到任何對boxes.add(...)的引用,所以任何使用boxes.get()的嘗試都會引發異常。

這完全不清楚爲什麼你認爲你需要一個List<List<Integer>>。多維列表通常是代碼味道。在99%的情況下,使用自定義對象的不同數據結構將更爲合適。

+1

感謝您的錯字修復@Tom –