首页 文章

2D数组没有正确地遵循row和col维度 - Java

提问于
浏览
0

我正在为类创建一个小的java程序,它从文件中获取一个int和double的列表并将它们构建成一个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工作) .

3 回答

  • 0
    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,(lenghth是多少行);.

    colulmns =行是多么离开(array [row] .length .

  • 0

    将你的循环改为:

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

    应该这样做 .

  • 1

    一个明显的错误是在内循环中,使用 array[i].length 而不是 array.length

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

相关问题