I have been trying to figure this out for a while and need some help. I need to find the min/max values and print them out for a multidimensional array. Here are the two ways that I have tried.
import java.util.*;
class MinMax {
public static void main(String[] args) {
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}};
Arrays.sort(data);
System.out.println("Minimum = " + data[0]);
System.out.println("Maximum = " + data[data.length - 1]);
}
}
This version complies but doesn't run.
import java.util.*;
class MinMax {
public static void main(String[] args) {
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}};
public static int getMaxValue(int[] numbers) {
int maxValue = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > maxValue) {
maxValue = numbers[i];
}
return maxValue;
{
public static int getMinValue (int[] numbers) {
int minValue = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < minValue) {
minValue = numbers[i];
}
}
return minValue;
}
This version just throws me a bunch of errors in compiling. Any help is greatly appreciated.
package array;
public class Max_number {
}
Ok, I've kinda fixed your code. Actually your mistake was that you have not been traversing all the cells of your multidimensional array.
So, I've added additional loop into getMinValue/getMinValue methods and fixed array elements addressing.
I have a more fun solution using Java 8 :)
It's a different solution than yours, obviously. But it does the same thing. To begin with, we convert the 2D array into a
Stream
ofint
s. In order to do this first we need to callflatMapToInt
. We do this to stream all the elements in the array in a flat way. Imagine if we just start using a single index to iterate over the whole 2D array. It's something like that. Once we have converted the array into a stream, we will use IntSummaryStatistics in order to reuse the same stream for both min and max.Your problem is: You are sorting the array of
int
arrays instead of sorting each individualint
in eachint
array.To solve this: Loop through each
int
array in the array ofint
arrays.Instructions for finding the maximum and minimum of a 2D
int
array usingArrays.sort()
:int
array to sort calleddata
.int
s, one to hold the maximum value, the other the minimum value.Integer.MIN_VALUE
and the initial value of the minimum should beInteger.MAX_VALUE
to make sure that negative values are handled.data
from0
todata.length
:data[i]
data[i]
is less than the minimum and change it if it is.data[i]
is greater than the maximum and change it if it is.Example: