设计一个名为
Location
的类, 定位二维数组中的最大值及其位置
。
这个类包括公共的数据域
row
、
column
和
maxValue
,
二维数组中的最大值及其下标用
int
型的
row
和
column
以及
double
型的
tnaxValue
存储
。
编写下面的方法, 返回一个二维数组中最大值的位置 。
public static Location 1 ocateLargest (double[][] a)
返回值是一个 Location 的实例 。 编写一个测试程序 , 提示用户输人一个二维数组 . 然后显示这个数组中最大元素的位置 。
编写下面的方法, 返回一个二维数组中最大值的位置 。
public static Location 1 ocateLargest (double[][] a)
返回值是一个 Location 的实例 。 编写一个测试程序 , 提示用户输人一个二维数组 . 然后显示这个数组中最大元素的位置 。
import java.util.Scanner;
public class E13 {
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.println("Enter the number of rows and columns in the array: ");
int rows=input.nextInt();
int columns=input.nextInt();
double[][] b=new double[rows][columns];
System.out.println("Enter the array:");
for(int i=0;i<rows;i++){
for(int j=0;j<columns;j++){
b[i][j]=input.nextDouble();
}
}
Location ddd=Location.locateLargest(b);
System.out.println("The location of the largest element is "+
ddd.maxValue+ " at ("+ddd.row+","+ddd.column+")");
}
}
class Location{
public int row;
public int column;
public double maxValue;
public Location(int ro,int co,double ma){
row=ro;
column=co;
maxValue=ma;
}
public static Location locateLargest (double[][] a){
double maxNumber=0;
int rowId=0;
int columnId=0;
for(int i=0;i<a.length;i++){
for (int j=0;j<a[i].length;j++){
if (a[i][j]>maxNumber){
maxNumber=a[i][j];
rowId=i;
columnId=j;
}
}
}
return new Location(rowId,columnId,maxNumber);
}
}