0

I wrote a class that has a 2d array that grows based on user input and allows user to enter numbers in array. The user would enter 2 2 for the size and 2 4 5 4 for the numbers It would print out like this

2 2 
2 2

It works until I enter an array size 7 1 , 7 rows and 1 column. I get an Exception

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at Assignment7.main(Assignment7.java:55)

I don’t understand why

import java.util.Scanner;
public class Assignment7 
{
public static void main(String[] args) 

    {




    Scanner scan = new Scanner(System.in);

    System.out.print(" ");

    int [][] nums = new int[scan.nextInt()][scan.nextInt()];


    System.out.print(" ");

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

        for (int j = 0; j < nums.length; ++j)

            {

            nums[i][j] = scan.nextInt();

            }           
        }           

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

        {

            System.out.print("\n");

        for (int j = 0; j < nums.length; ++j)

        {

            System.out.print(nums[i][j]);

         }

        }

    }               
}

2 Answers 2

3

second dimension's length should be nums[i].length, Note: (i for your example)

Sign up to request clarification or add additional context in comments.

Comments

1

For your inner loop, you're using the size of the outer array:

for (int i = 0; i < nums.length; ++i)
    {
    for (int j = 0; j < nums.length; ++j)

This should be:

for (int i = 0; i < nums.length; ++i)
    {
    for (int j = 0; j < nums[i].length; ++j)

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.