java黑皮书课后习题9.13

/**
 * 定位二维数组最大值及其位置
 */
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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值