繁体   English   中英

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

[英]Deal Or No Deal Game Java ArrayList issues

我正在尝试用Java制作基本的“交易或不交易”游戏。 我在添加和删除多维数组列表时遇到问题。 问题出现在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();
    }
}

您创建

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

但这不会将任何内容放入ArrayList 我在您的代码boxes.add(...)不到对boxes.add(...)引用,因此任何使用boxes.get()尝试都会引发异常。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM