簡體   English   中英

2D數組未正確遵守行和列尺寸-Java

[英]2D array is not adhering to row and col dimensions correctly - Java

我正在為類創建一個小型Java程序,該程序將一個int列表從文件中提取並加倍,並將它們構建為2D數組,然后對該數組進行排序。 該文件將是這樣的,

4
5
3.00
5.67
4.56
etc

前兩個整數被用作數組的行和列大小,其余的雙精度數被填充到數組中。 但是,當行和列的尺寸是兩個不同的數字時(例如5x4而不是4X4),讓我的程序創建數組時遇到問題。 我意識到我一定會丟失一些東西,但是我不確定是什么。 這是我的方法,該方法讀取文件並將其構建到數組中:

    public static double[][] readFile(String fileName) throws FileNotFoundException {
    Scanner reader = new Scanner(new FileReader(fileName + ".txt"));
    int row = reader.nextInt();
    int col = reader.nextInt();
    double[][] array = new double[row][col];
    for(int i = 0; i < array.length; i++){
        for(int j = 0; j < array.length; j++){
            array[i][j] = reader.nextDouble();
        }
    }
    return array;

}  

任何提示將不勝感激。 請注意,我確保文件中有足夠的雙倍量可讀取到5x4等數組中。 同樣,這僅在行大於col時才會出錯(因此4x5有效)。

一個明顯的錯誤是在內部循環中,使用array[i].length而不是array.length

for(int j = 0; j < array[i].length; j++){
    array[i][j] = reader.nextDouble();
}
 But I am having a problem getting my program to create the arrays when the row
 and col dimensions are two different numbers, as in 5x4 rather than 4X4.

您需要在循環中進行微妙的更改。

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

改成

for(int i = 0; i < array.length; i++){
    for(int j = 0; j < array[row].length; j++){  // notice subtle change

rows = array.length,(長度是多少行);

colulmns =行的長度(array [row] .length。

將您的循環更改為此:

for(int i = 0; i < array.length; i++){
    for(int j = 0; j < array[i].length; j++){
        array[i][j] = reader.nextDouble();
    }
}

應該這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM