首页 > 解决方案 > Java:关于定位最小位置的矩阵的一些错误

问题描述

这是我所做的

    java.util.Scanner input = new java.util.Scanner(System.in);

    System.out.print("Rnter the number if rows and columns of the array: ");
    int row = input.nextInt();
    int col = input.nextInt();
    
    double numList[][] = new double[row][col];
    
    System.out.println("Enter the array:");
    for(int i = 0; i < row; i++){
        for(int j = 0; j < col; j++){
            numList[i][j] = input.nextDouble();
        }
    }
    int[] location;
    location = locateSmallest(numList);
    System.out.println("The location of the smallest element is at " + Arrays.toString(location));
}
    public static int[] locateSmallest(double[][] a){
    int i, j;
    double minNum = a[0][0];
    int minNumLocate[] = new int[2];
    for (j = 0; j < a.length; j++){       
        for (i =0; i < a[j].length; i++){
            if (a[j][i] < minNum){
                minNumLocate[j] = j;
                minNumLocate[i] = i;
             }
        }
    }
    return minNumLocate;   
}
    

}

总的来说,应该为 int 输入完成,就像这里

   Enter the number if rows and columns of the array: 3 4
   Enter the array:
   1 2 3 4
   3 4 5 6
   3 4 5 6
   The location of the smallest element is at [0, 0]

但我输入双重输入,它出现错误,就像这里

Enter the number if rows and columns of the array: 3 4
Enter the array:
1.5 3 2 10
3.5 4 2 1
35 44 5.5 9.6
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 2

我不知道我应该在哪里更正,请帮我检查一下,如果可以的话,请帮我检查一下我在哪里可以同时改进得更清楚谢谢大家

标签: java

解决方案


a[j].length将是 3 并且int minNumLocate[]暗淡等于 2。所以没有什么可以保护 j 或 i 低于 2。

只需更改您在 minNumLocate assignment 上定义索引的方式:

    int minNumLocate[] = new int[2];
    for (j = 0; j < a.length; j++){       
        for (i =0; i < a[j].length; i++){
            if (a[j][i] < minNum){
                minNumLocate[1] = j;
                minNumLocate[0] = i;
             }
        }
    }

此外,缺少minNum找到的最小值的更新。

    int minNumLocate[] = new int[2];
    for (j = 0; j < a.length; j++){       
        for (i =0; i < a[j].length; i++){
            if (a[j][i] < minNum){
                minNumLocate[1] = j;
                minNumLocate[0] = i;
                minNUm = a[j][i];
             }
        }
    }

最后一次优化,将使用输入中的colrow

     int minNumLocate[] = new int[2];
     minNUm = a[0][0];
     for (j = 0; j < row ; j++){       
        for (i =0; i < col; i++){
            if (a[j][i] < minNum){
                minNumLocate[1] = j;
                minNumLocate[0] = i;
                minNUm = a[j][i];
             }
        }
    }


推荐阅读