user2227728
user2227728

Reputation: 15

Runtime Exception while with 2d array

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

         }

        }

    }               
}

Upvotes: 0

Views: 153

Answers (2)

Darshan Rivka Whittle
Darshan Rivka Whittle

Reputation: 34031

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)

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240860

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

Upvotes: 3

Related Questions