Runtime Exception while with 2d array

假装没事ソ 提交于 2019-12-24 20:38:51

问题


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

         }

        }

    }               
}

回答1:


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




回答2:


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)


来源:https://stackoverflow.com/questions/16222519/runtime-exception-while-with-2d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!