当前位置: 动力学知识库 > 问答 > 编程问答 >

java - 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!

分享给朋友:
您可能感兴趣的文章:
随机阅读: