使用Array列表来指定另一个Array列表的索引

时间:2017-10-24 03:00:20

标签: java arraylist

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    ArrayList <SlotMachine> machines = new ArrayList<SlotMachine>();
    System.out.print("How many machines are they playing?: ");
    int machinesNeeded = scan.nextInt();
    int machineCounter = 1;
    for (int i = 0; i < machinesNeeded; i++) {
        machines.add(new SlotMachine());
        System.out.print("How often does machine # " + machineCounter + " pay its jackpot?: ");
        machines.get(i).setPayOutTime(scan.nextInt());
        System.out.print("How much is the jackpot for machine # " + machineCounter + ": ");
        machines.get(i).setPayOut(scan.nextInt());
        System.out.print("How many times has machine # " + machineCounter + " been played since paying out?: ");
        machines.get(i).setTimesPlayed(scan.nextInt());
        machineCounter ++;
    }

    ArrayList <Integer> machineOrder = new ArrayList<Integer>();
    machineOrder.add(3);
    System.out.print("Enter machine to use: ");
    System.out.println(machines.get(machineOrder.get(0)));

我想使用machineOrder列表变量中的值作为访问计算机值的索引。 不知道该怎么做我继续得到

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3   

1 个答案:

答案 0 :(得分:1)

您的代码存在缺陷,您正在添加machine.add(3),因此您的machine.get(0)始终返回3,您可以添加3台机器作为数组索引从0最大索引开始是2,你试图访问第3个元素因此你得到java.lang.IndexOutOfBoundsException