交易或不交易游戏Java ArrayList问题

时间:2016-05-21 14:39:43

标签: java

我试图做一个基本的"交易或不交易" Java中的游戏。我遇到了添加和删除我的多维arraylist的问题。 问题发生在shuffleBoxes()的第7行和playerBox()的第9行。

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();
    }
}

1 个答案:

答案 0 :(得分:3)

您创建

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

但这并没有在ArrayList中添加任何内容。我在您的代码中看不到对boxes.add(...)的任何引用,因此任何使用boxes.get()的尝试都会引发异常。

您认为自己需要List<List<Integer>>的原因并不清楚。多维列表通常是代码气味。在99%的情况下,使用自定义对象的不同数据结构将更合适。

相关问题