繁体   English   中英

具有用户输入和随机数的2D数组

[英]2D Array with user input and random numbers

我正在尝试生成一个要求用户输入数字“ n”并显示2 xn数组的程序。 例如:

1 2 3 4 5(用户输入)

5 8 2 1 5(随机数字)

我看不到使我的代码正常工作。 这是我的代码:

import java.util.Scanner;


public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {



        Scanner input = new Scanner(System.in);
        System.out.print("Enter number of exits: ");
        int n = input.nextInt();

        int [][] A = new int[2][n];
        for (int i =0; i <= A[n].length; i++){

            A[i][n]= (int)(Math.random()*10);
    }
        System.out.println(A[2][n]);
        System.out.print("Distance between exit i and exit j is: " + distance());
    }



    public static int distance(){
        Scanner input = new Scanner(System.in);

        System.out.print("Please enter exit i: ");
        int i = input.nextInt();
        System.out.print("Please enter exit j: ");
        int j = input.nextInt();
        return i + j;
    }
}

我收到此错误

“线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:5”

我该如何解决? 而且我认为我的Math.random是错误的。 你们能为我提供一些建议还是我在哪里做错了事? 谢谢。

您的所有错误都在for循环之内和之后:

for (int i =0; i <= A[n].length; i++){

        A[i][n]= (int)(Math.random()*10);
}

如果n = 5,则不存在A [5] .length,因为数组的第一个维仅存在于0和1之间。A[2]保留2个int图元的空间,第一个在索引0处,最后一个在索引处在索引1处。即使已更改,for循环声明的i变量也将增加到1以上,因此JVM将抛出ArrayIndexOutOfBoundsException。

在声明尺寸为[2] [n]的数组时(假设n为整数,这将由用户通过扫描仪提供),您将无法访问arrayReference [2] [x]

数组基于0索引结构 ...

考虑以下:

int [] [] A =新的int [2] [2];

您只能访问A [0] [0],A [0] [1],A [1] [0]和A [1] [1]。

不能访问A [2] [0],A [2] [1]或A [2] [2]。


这是您需要做的:

 //A.length will give you the length of the first dimension (2)
 for(int i=0; i<A.length; i++){
            for(int j=0; j<n; j++){
                A[i][j] = (int) (Math.random()*10);
            }
        }
    }
 System.out.println(A[1][n-1]);
 System.out.print("Distance between exit i and exit j is: " + distance());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM