面向对象-设计一个Location类

问题

设计一个名为Location的类,定位二维数组中的最大值及其位置。这个类包括公共的数据域row、 column和maxValue,二位数组中的最大值及其下标用int型的row和column以及double型的maxValue 存储。(5分) 编写下面的方法,返回一个二位数组中最大值的位置。 public static Location locateLargest(double[][] a) 返回值是一个Location的实例。

下面是自己写的相关代码:

package com.edu.hpu;

class Location{
	private int row;
	private int column;
	private int maxValue;
	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 int getMaxValue() {
		return maxValue;
	}
	public void setMaxValue(int maxValue) {
		this.maxValue = maxValue;
	}

	public  Location getLargest(int[][] array){
		int row=0;
		int column=0;
		//int[][] a=new int[row][column];
		int maxValue=array[0][0];
		for(int i=0;i<array.length;i++){
			for(int j=0;j<array[0].length;j++){
				if(maxValue<array[i][j]){
					row=i;
					column=j;
					maxValue=array[row][column];
				}
			}
		}
		Location ic=new Location();
		ic.row=row;
		ic.column=column;
		ic.maxValue=maxValue;
		ic.getRow();
		ic.getColumn();
		ic.getMaxValue();
		//System.out.println(ic.getRow());
    	return ic;
    	
	}
	
}

public class MaxValue {

	public static void main(String[] args) {
		
		int[][] a={{4,5,8},{55,22,10},{36,12,20}};
		Location ic=new Location();
		ic=ic.getLargest(a);
		System.out.println("该数组的最大值为:"+ic.getMaxValue()+","+"它的行为:"+ic.getRow()+"它的列为:"+ic.getColumn());

	}

}

运行结果:

下面是在论坛看到的(不太明白):
package test3; 
 
public class Location { 
	private static int row ; 
	private static int column ; 
	private static double maxValue; 
	 
	public Location(int row,int column,double maxValue){ 
		this.row=row; 
		this.column=column; 
		this.maxValue=maxValue; 
	} 
	 
	public String toString(){ 
		return "行="+this.row+" 列="+this.column+" 最大值="+this.maxValue; 
	} 
	 
	 
	//静态方法实际上不应该这样返回自身的实例 
	//但是你命题这样写的,只能硬着头皮这么做了 
	public static Location locateLargest(double[][] a){ 
		row=0; 
		column=0; 
		maxValue=a[0][0]; 
		//遍历二维数组 
		for(int i = 0;i<a.length;i++){ 
			 
			for(int j=0;j<a[i].length;j++){ 
				if(a[i][j]>maxValue){ 
					row=i; 
					column=j; 
					maxValue=a[i][j]; 
				} 
			} 
		} 
		return new Location(row,column,maxValue); 
	} 
	 
	public static void main(String args[]){ 
		double[][] a = new double[3][3]; 
		for(int i=0;i<a.length;i++){ 
			for(int j=0;j<a[i].length;j++){ 
				a[i][j]=(i+1)*(j+1); 
			} 
		} 
		 
		System.out.println(Location.locateLargest(a)); 
	} 
 
}

  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值