繁体   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