簡體   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