0

// Java: How to represent 1d string/int array into 2d int array? I would really appreciate your help.

package intro;
public class ArrayTest{

    public static void main(String[] args) {

        int arr[][]= new int[4][4];   
        int month_days [] = {31,28,31,30,31,30,31,31,30,31,30,31,13,14,15,16};

        int size =4;
        //System.out.println(size);
        for (int i = 0, k = 0; i < size; i++, k++) {
            for(int j=0; j <size; j++){
                arr[i][j]= month_days[k++];

                //System.out.println(month_days[k++] + " ");
                System.out.print(arr[i][j] + " ");
            }

            System.out.println();
        }
    }
}
4
  • 31 28 31 30 30 31 31 30 30 31 13 14 16 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 16 at intro.ArrayTest.main(ArrayTest.java:13) Commented Sep 28, 2013 at 0:18
  • Learn to use debugging tools. Commented Sep 28, 2013 at 0:19
  • What line is number 13? ArrayTest.java:13 refers to the class (ArrayTest.java) and line number (13) in which the error occurs. Commented Sep 28, 2013 at 0:20
  • 1
    You are incrementing k in two places. (And three if you uncomment the print statement) Commented Sep 28, 2013 at 0:22

3 Answers 3

5

You increment k too often. You increment it in the for-loop and here: month_days[k++].
Remove the increment from the for-loop:

for (int i = 0, k = 0; i < size; i++)
0
1

Change arr[i][j] = month_days[k++]; to arr[i][j] = month_days[k];

Every instance of k++ is incrementing k by 1. Currently, you're incrementing it twice per iteration of your for loop, so after the 8th iteration, it's looking to put the 17th element of month_days[] into arr[][], but month_days[] doesn't have that many elements.

0

You are already incrementing your 'k' variable in this line: month_days[k++];

You don't need to increment it in this line as well: for (int i = 0, k = 0; i < size; i++, k++) {

Basically, you are throwing away a 'k' value each time your loop runs, which makes you run out of values before you can fill your array.

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.