简体   繁体   中英

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

I am creating a small java program for class that takes in a list of ints and doubles from a file and builds them into a 2D array, then sorts the array. The file would be something like,

4
5
3.00
5.67
4.56
etc

The first two ints are taken as the row and column sizes for the array, and the rest of the doubles are filled into the array. 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. I realize I must be missing something, but I am not sure what. Here is my method that reads the file and builds it into the array:

    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;

}  

Any tips would be appreciated. Note that I have made sure that there are the sufficient double amounts in the file to be read into a 5x4 etc. array. Also this only errors when the row is bigger than the col (so 4x5 works).

An obvious mistake is in the inner loop, use array[i].length rather than 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.

You need to make a subtle change in your loop.

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

Change to

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

rows = array.length, (lenghth is how many rows);.

colulmns = how lon the row is (array[row].length.

Change your loop to this:

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

that should do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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