第八章第十三题(定位最大的元素)(Locate the largest element)
-
*8.13(定位最大的元素)编写下面的方法,返回二维数组中最大元素的位置。
public static int[] locateLargest(double[][] a)
返回值是包含两个元素的一维数组。这两个元素表示二维数组中最大元素的行下标和列下标。编写一个测试程序,提示用户输入一个二维数组,然后显示这个数组中最大元素的位置。下面是一个运行示例:
Enter the number of rows and columns of the array:3 4
Enter the array:
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)
*8.13(Locate the largest element)Write the following method to return the position of the largest element in a two-dimensional array.
public static int[] locateLargest(double[][] a)
The return value is a one-dimensional array of two elements. These two elements represent the row and column subscripts of the largest element in a two-dimensional array. Write a test program, prompt the user to input a two-dimensional array, and then display the position of the largest element in the array. Here is a running example:
Enter the number of rows and columns of the array:3 4
Enter the array:
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) -
参考代码:
package chapter08; import java.util.Scanner; public class Code_13 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the number of rows and columns of the array:"); int rows = input.nextInt(); int columns = input.nextInt(); System.out.println("Enter the array:"); double[][] array = new double[rows][columns]; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { array[i][j] = input.nextDouble(); } } int[] largestLocation=locateLargest(array); System.out.println("The location of the largest element is at ("+largestLocation[0]+","+largestLocation[1]+")"); } public static int[] locateLargest(double[][] a) { int[] max = new int[2]; double largest=a[0][0]; for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ if(largest<a[i][j]){ largest=a[i][j]; max[0]=i; max[1]=j; } } } return max; } }
-
结果显示:
Enter the number of rows and columns of the array:3 4 Enter the array: 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) Process finished with exit code 0