2
I’m trying to get the lowest and highest value of each line in a two-dimensional array with java, but I’m getting the incorrect values. Follows the code:
int[][] arrayValues = {
{ 21, 33, 70, 16, 70, 80, 67, 21 },
{ 54, 93, 36, 80, 48, 41, 14, 5 },
{ 6, 91, 81, 14, 37, 91, 98, 35 },
{ 51, 20, 54, 46, 59, 72, 65, 79 },
{ 4, 34, 95, 74, 14, 61, 94, 68 }
};
int min = arrayValues[0][0];
int max = arrayValues[0][0];
int[] minValue = new int[arrayValues.length];
int[] maxValue = new int[arrayValues.length];
for (int i = 0; i < arrayValues.length; i++) {
for (int j = 0; j < arrayValues[i].length; j++) {
if (arrayValues[i][j] < min) {
minValue[i] = arrayValues[i][j];
}
if (arrayValues[i][j] > max) {
maxValue[i] = arrayValues[i][j];
}
}
System.out.println("Min: " + minValue[i] + " Max: " + maxValue[i]);
}
The minimum returned values are: 16, 14, 14, 20 and 14 and the maximum ones: 67, 50, 35, 79 and 68, but the minimum ones should be: 16, 14, 6, 20 and 14 and the maximum ones: 80, 93, 98, 79 and 95. I don’t know what I’m doing wrong, since in some lines it gets the right value.
You want the biggest and smallest of each line use
for (int i = 0; i < arrayValues.length; i++) { int min = arrayValues[i][0]; int max = arrayValues[i][0]; for (int j = 0; j < arrayValues[i].length; j++) {
and not once for any array.– anonimo