我试图在2D数组中找到具有最小和的行,但我只得到0

时间:2021-10-01 02:18:28

Why do I get 0's for minRow and minRowIndex? Thank you whoever response.

为什么我得到minRow和minRowIndex的0?谢谢谁回复。

import java.util.Scanner;

public class test1 {

public static void main(String[] arg) {

    Scanner in = new Scanner(System.in);

    int [][] matrix = {{1, 2, 3, 4, 5}, {2, 3, 4, 5, 6}, {3, 4, 5, 6, 7}};

    int minRow = 0;
    int minRowAvg = 0;
    int minRowIndex = 0;

    for (int row = 1; row < matrix.length; row++){
        int rowSum = 0;
        for (int col = 0; col < matrix[row].length; col++){
            rowSum += matrix[row][col];
        }

        if (rowSum < minRow && rowSum > 0){ 
            minRow = rowSum;
            minRowIndex = row;
        }
    }
    System.out.println("Row " + minRowIndex + " has the minimum sum of " + minRow);

    }

}

2 个解决方案

#1


2  

rowSum will never be smaller the minRow, since you initialized minRow to 0.

rowSum永远不会小于minRow,因为你将minRow初始化为0。

You should initialize it to Integer.MAX_VALUE.

您应该将其初始化为Integer.MAX_VALUE。

int minRow = Integer.MAX_VALUE;

#2


0  

First of all, in your first loop, the row variable starts at 1 so you never check your first matrix row, it should start at 0.

首先,在第一个循环中,行变量从1开始,因此您永远不会检查第一个矩阵行,它应该从0开始。

Your minRow is initialized at 0 and is only modified in your

你的minRow初始化为0,只在你的

if (rowSum < minRow && rowSum > 0){ 
        minRow = rowSum;
        minRowIndex = row;
}

Your condition is always false because rowSum is always superior to minRow. This is the same issue with your minRowIndex.

您的条件始终为false,因为rowSum始终优于minRow。这与您的minRowIndex相同。

#1


2  

rowSum will never be smaller the minRow, since you initialized minRow to 0.

rowSum永远不会小于minRow,因为你将minRow初始化为0。

You should initialize it to Integer.MAX_VALUE.

您应该将其初始化为Integer.MAX_VALUE。

int minRow = Integer.MAX_VALUE;

#2


0  

First of all, in your first loop, the row variable starts at 1 so you never check your first matrix row, it should start at 0.

首先,在第一个循环中,行变量从1开始,因此您永远不会检查第一个矩阵行,它应该从0开始。

Your minRow is initialized at 0 and is only modified in your

你的minRow初始化为0,只在你的

if (rowSum < minRow && rowSum > 0){ 
        minRow = rowSum;
        minRowIndex = row;
}

Your condition is always false because rowSum is always superior to minRow. This is the same issue with your minRowIndex.

您的条件始终为false,因为rowSum始终优于minRow。这与您的minRowIndex相同。