1

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

    }
}
2
  • 2
    How is this obvious duplicate upvoted 3 times(at least)? Commented Oct 7, 2015 at 15:05
  • 4
    Possible duplicate of Java: Array Index Out of Bounds Exception Commented Oct 7, 2015 at 15:06

3 Answers 3

2

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++)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.