【问题标题】:How to get Maximum value in multiple array?如何获得多个数组中的最大值?
【发布时间】:2019-06-21 02:30:19
【问题描述】:

我想取从result.length中得到的最大值,但是我在调​​用它的方式上遇到了麻烦,你能帮帮我吗?

double[][] result =  matrixMultiplexing(neighboursAdjSquare(matrixEgoNetwork), matrixDecrement(ones, matrixEgoNetwork));
double max = result[0][0];
    ArrayList<Double> val= new ArrayList<>();
    for (int i = 0; i < result.length; i++) {
        for (int j = i+1; j < result.length; j++) {
            Arrays.sort(result);
            if(result[i][j]== "I wanna called here" ){

                    val.add(result[i][j]);

            }
        }
    }

错误是不能应用'double',double[]' 你能帮我解决这个问题吗?

【问题讨论】:

  • 你想从每个数组中获取最大值,还是只获取一个最大值?
  • Arrays.stream(result).flatMapToDouble(Arrays::stream).max()?
  • 我想得到唯一的一个最大值,来自 result[i][j] 先生。
  • 你为什么将 double 与 String 这里的 result[i][j]== "I wanna called here" 进行比较?这甚至不会编译。

标签: java arrays matrix max one-simulator


【解决方案1】:
public class FindMaxOf2dArray {
public static void main(String[] argv) {
    double[][] arr2d =  new double[][]{
        {1.0, 2.0, 3.0, 4.0},
        {5.0, 6.0, 7.0, 8.0},
        {99.0, 0.0, 0.0, -1.0}
    };
    double maxOfarr2d = findMaxOf2dArray(arr2d);

    System.out.println("The maximum value contained in arr2d is " + maxOfarr2d);
}

static double findMaxOf2dArray(double[][] arr2d){
    double maxValue = Double.MIN_VALUE; 

    for(int i = 0; i < arr2d.length; i++){ //iterate through the number of arrays 
        for(int j = 0; j < arr2d[i].length; j++){//iterate through each value in the given array
            if(arr2d[i][j] > maxValue){
                maxValue = arr2d[i][j];
            }
        }
    }

    return maxValue;
}

}

这将是在二维数组中找到最大值的最直接方法。不一定是最好的方法,但应该很容易遵循逻辑。在 findMaxOf2dArray(double[][]) 方法中,我们将最大值设置为可以存储在 double 中的最小可能值。然后我们进入一个循环遍历每个包含双精度值的数组的 for 循环。对于此循环的每次迭代,我们都会进入第二个 for 循环,该循环遍历存储在当前数组中的每个值。然后将每个值与存储在 maxValue 中的值进行比较。如果存储在数组中的值大于存储在 maxValue 中的值,那么我们将 maxValue 的值更改为存储在数组中的值。最后检查二维数组的每个数组中的每个值后,我们返回存储在 maxValue 中的值。

我认为您的代码的问题在于您从不遍历存储在每个数组中的值。你只遍历数组本身——两次。存储在 result[i] 中的每个值本身就是一个数组,其中包含要比较的双精度值。此外,通过从 i + 1 开始 j ,您可以跳过 i + 1 个要迭代的值。最后,不能将 double 与 String 进行比较。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多