/**
* 定位二维数组最大值及其位置
*/
public class Exercise09_13 {
public static void main(String[] args) {
java.util.Scanner sc = new java.util.Scanner(System.in);
/*用户输入二维数组的行,列*/
System.out.println("Enter the number of rows and columns in the array:");
int row = sc.nextInt();
int column = sc.nextInt();
/*用户输入数组值*/
double[][] array2D = new double[row][column];
System.out.println("Enter the array:");
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
array2D[i][j] = sc.nextDouble();
}
}
/*创建对象用于存储Location类中静态方法返回的对象*/
Location location = Location.locateLargest(array2D);
/*输出*/
System.out.println("The location of the largest element is " + location.getMaxValue() +
" at " + "(" + location.getRow() + "," + location.getColumn() + ")");
}
}
class Location {
/*私有数据域*/
private int row;//存储最大值的行下标
private int column;//存储最大值的列下标
private double maxValue;//存储最大值
/*1.方法可以返回对象
2.多维数组行列未知时也可以使用
3.在静态方法内可以通过构造对象调用实例变量与方法
*/
public static Location locateLargest(double[][] a) {
//在静态方法内通过构造对象调用实例变量与方法
Location location = new Location();
//暂定下标[0][0]为最大值
location.maxValue = a[0][0];
//在多维数组中搜索最大值及其下标并替换
for (int row = 0; row < a.length; row++) {
for (int column = 0; column < a[row].length; column++) {
if (a[row][column] > location.maxValue) {
location.maxValue = a[row][column];
location.row = row;
location.column = column;
}
}
}
return location;
}
/*数据域的访问器和修改器*/
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
public int getColumn() {
return column;
}
public void setColumn(int column) {
this.column = column;
}
public double getMaxValue() {
return maxValue;
}
public void setMaxValue(double maxValue) {
this.maxValue = maxValue;
}
}
java黑皮书课后习题9.13
最新推荐文章于 2022-10-24 11:04:46 发布