简体   繁体   中英

2D Array Index Out of Bounds Exception issue

I'm working on a program to generate a schedule; I've gotten it to accept user input for who the employees are by adding them to a list, but when I try to move the items from the list to the double array, I get an Array Index Out of Bounds Exception. What can I do here to solve this issue, I've tried about everything else I can think of.

import java.util.*;

public class schedule
{

    public static void main(String[] args)
    {
        Scanner readme = new Scanner(System.in);
        List<String> employees = new ArrayList<String>();
        //accepts input for list
        while(true)
        {
            System.out.println("Employees are: " + employees);
            System.out.println("Are there more? (y/n)");
            if (readme.next().startsWith("y"))
            {
                System.out.println("Who?");
                employees.add(readme.next());
            }
            else
            {
                //creates a double array the size of the employees list by the number of shifts in the week
                String[][] scheduleArr = new String[employees.size()][14];
                //adds items from array to corresponding spot on double array
                for (int i = 0; i <= scheduleArr.length; i++)
                {
                    scheduleArr[i][0] = employees.get(i);
                }
                System.out.print(scheduleArr[0][0]);
            }
        }

    }
}

Array indices start at 0 and end at length - 1.

Change

for (int i = 0; i <= scheduleArr.length; i++)

to

for (int i = 0; i < scheduleArr.length; i++)

You should iterate from 0 to length-1 not length (arrays are 0 based)

        for (int i = 0; i < scheduleArr.length; i++) //NOT i <= scheduleArr.length
        {
            scheduleArr[i][0] = employees.get(i);
        }

Modify your code to

for (int i = 0; i < scheduleArr.length; i++) //NOT i <= scheduleArr.length
        {
            scheduleArr[i][0] = employees.get(i);
        }

or

for (int i = 1; i <= scheduleArr.length; i++) //NOT i <= scheduleArr.length
        {
            scheduleArr[i][0] = employees.get(i);
        }

Both will do the need for you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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