Java實驗(8) Location類

定義一個Location類,用於搜索二維數組的最大元素出現的位置和值。位置用公有的整型成員變量row, col表示,最大值用公有的浮點型成員變量maxValue表示。一個成員方法用來求解二維數組的最大元素及其位置,原型如下:

public static Location locateLargest(double[][] a)

例如數組爲{{1,2,3},{8,9,9,5},{4,3,5,7,8}},最大元素爲9,位置是(1,1)。注意最大值不止一個的時候,只記錄第一次出現的位置。

請提供一個測試類,測試上述方法。






import java.util.Scanner;
class Location
{
    public int row,col;
    public double maxValue;
    //構造函數
    Location(){}
    Location(int r,int c,double mv){
        row=r;
        col=c;
        maxValue=mv;
    }
    //找最大的位置
    public static Location locateLargest(double [][]a){
        double maxValue=a[0][0];
        int row=0,col=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;
                    col=j;
                    maxValue=a[i][j];
                }
            }
        }
        Location lo=new Location(row,col,maxValue);
        return lo;
    }
}
public class LocationMax {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        Location l=new Location();
        System.out.println("請輸入數組的行數:");
        int r=input.nextInt();
        double [][]a=new double[r][];
        //因爲數組可能不規則,所以對每行都要確定一個列數
        for(int i=0;i<r;i++){
            System.out.println("請輸入數組第"+i+"行的列數:");
            int c=input.nextInt();
            a[i]=new double[c];
        }
        System.out.println("請輸入數組");
        for(int i=0;i<r;i++){
            for(int j=0;j<a[i].length;j++){
                a[i][j]=input.nextDouble();
            }
        }
        l=l.locateLargest(a);
        System.out.println("行:"+l.row);
        System.out.println("列:"+l.col);
        System.out.println("最大值:"+l.maxValue);
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章