Problem:
Write the following method that returns the location of the largest element in a two-dimensional array.
public static int[] locateLargest(double[][] a)
The return value is a one-dimensional array that contains two elements. These two elements indicate the row and column indices of the largest element in the two dimensional array. Write a test program that prompts the user to enter a two-dimensional array and displays the location of the largest element in the array.
Output:
23.5 35 2 10
4.5 3 45 3.5
35 44 5.5 9.6
The location of the largest element is at (1, 2)
4.5 3 45 3.5
35 44 5.5 9.6
The location of the largest element is at (1, 2)
Solution:
import java.util.Scanner; public class LargestElement { public static int[] locateLargest(double[][] a) { double max = a[0][0]; int i1 =0,j1=0; for (int i= 0;i <a.length;i++) { for (int j =0; j<a[i].length;j++) { if (a[i][j] > max) { max = a[i][j]; i1 =i; j1 =j; } } } int[] bla = {i1,j1}; return bla; } public static void main (String[] args) { Scanner scan = new Scanner (System.in); System.out.print("Enter the number of rows " + "and columns of the array: "); double[][] nums = new double[scan.nextInt()][scan.nextInt()]; System.out.println("Enter the array:"); for (int i =0;i<nums.length;i++) { for (int j =0;j<nums[i].length;j++) { nums[i][j] = scan.nextDouble(); } } int[] zizi = locateLargest(nums); System.out.println("The location of the largest element " + "is at (" + zizi[0] +", " +zizi[1] +")"); } }
No comments:
Post a Comment