**9.13(Location类)设计一个名为Location的类,定位二维数组中的最大值及其位置。这个类包括公共的数据域row、column和maxValue,存储二维数组中的最大值及其下标。row和column为int类型,maxValue为double类型。 编写下面的方法,返回一个二维数组中最大值的位置。 public static Location locateLargest(double[][] a) 返回值是一个Location的实例。编写一个测试程序,提示用户输入一个二维数组,然后显示这个数组中最大元素的位置。下面是一个运行示例: Enter the number of rows and columns in 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 45.0 at (1,2) *9.13(Location class)Design a class named location to locate the maximum value and its position in two-dimensional array. This class includes the common data fields row, column and maxvalue, which stores the maximum value and its subscript in a two-dimensional array. Row and column are of type int, and maxvalue is of type double. Write the following method to return the position of the maximum value in a two-dimensional array. public static Location locateLargest(double[][] a) The return value is an instance of location. 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 in 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 45.0 at (1,2)
参考代码:
package chapter09;import java.util.Scanner;publicclassCode_13{publicstaticvoidmain(String[] args){double[][] nums =newdouble[3][4];
System.out.print("Enter the number of rows and columns in the array: ");
Scanner cin =newScanner(System.in);int rows = cin.nextInt();int columns = cin.nextInt();
System.out.println("Enter the array: ");for(int i =0; i < rows;++i){for(int j =0; j < columns;++j){
nums[i][j]= cin.nextDouble();}}
Location location =locateLargest(nums);
System.out.println("The location of the largest element is "+ location.maxValue +" at ("+ location.row +","+ location.column +")");}publicstatic Location locateLargest(double[][] a){int x =0,y =0;double max =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];
x = i;
y = j;}}}
Location temp =newLocation();
temp.row = x;
temp.column = y;
temp.maxValue = max;return temp;}}classLocation{publicint row,column;publicdouble maxValue;}
结果显示:
Enter the number of rows and columns in the array:34
Enter the array:23.5352104.53453.535445.59.6
The location of the largest element is 45.0 at (1,2)
Process finished with exit code 0