To find the largest number in a 2D array in Java, you can use a loop to iterate over the elements of the array and compare each element to a variable holding the current largest number.
Here's an example of how to find the largest number in a 2D array in Java:
int[][] numbers = {{5, 3, 8}, {1, 9, 4}}; int largest = numbers[0][0]; for (int i = 0; i < numbers.length; i++) { for (int j = 0; j < numbers[i].length; j++) { if (numbers[i][j] > largest) { largest = numbers[i][j]; } } } System.out.println("The largest number is " + largest);
In the above example, a 2D array of integers is defined and initialized with two rows and three columns. A variable called largest
is initialized with the value of the first element in the array.
A nested loop is then used to iterate over the elements of the array. The outer loop iterates over the rows and the inner loop iterates over the columns. For each element in the array, the if
statement checks if the element is greater than the current value of largest
. If it is, the value of largest
is updated to the value of the element.
After the loops complete, the value of largest
is printed to the console.
Keep in mind that this example assumes that the array is not empty. If the array is empty or has no elements, the code will throw an ArrayIndexOutOfBoundsException
when it tries to access the first element. You should check the lengths of the arrays before iterating over them to avoid this exception.
For example:
int[][] numbers = {{}}; if (numbers.length == 0 || numbers[0].length == 0) { System.out.println("The array is empty"); } else { int largest = numbers[0][0]; for (int i = 0; i < numbers.length; i++) { for (int j = 0; j < numbers[i].length; j++) { if (numbers[i][j] > largest) { largest = numbers[i][j]; } } } System.out.println("The largest number is " + largest); }
In this example, the lengths of the arrays are checked before the loops are executed. If the array is empty or has no elements, a message is printed to the console stating