2D Array,如何查找每列最高值的所有者

时间:2017-10-18 14:14:03

标签: java arrays

我有一个功课,我需要与买家和产品一起创建2D阵列。每个产品和买家都有自己的编号,例如[buyer1] [product1],[buyer1] [product2],[buyer1] [product3]等。我需要从每一栏中找到最昂贵的产品并购买它。我找到了打印最贵产品的方法,但我不知道如何申报这些产品的买家

    public static void main(String[] args) {

    float arrayPrices[][];
    String arrayNames[];

    int c = 3;
    int n = 3;

    arrayNames = new String[c];

    arrayNames [0] = "John";       
    arrayNames [1] = "Jake";    
    arrayNames [2] = "Lucy";         

    arrayPrices = new float[c][n];
    arrayPrices [0][0] = 12;
    arrayPrices [0][1] = 2;
    arrayPrices [0][2] = 21;

    arrayPrices [1][0] = 132;
    arrayPrices [1][1] = 12;
    arrayPrices [1][2] = 1112;

    arrayPrices [2][0] = 32;
    arrayPrices [2][1] = 452;
    arrayPrices [2][2] = 125;


    for(int i = 0;i<c;i++){

    }

    for(int i = 0;i<c;i++){
         for(int j = 0;j<n;j++){

        }   

    }       

    String BuyerName;
    float MaxPrice = 0.0f;

    for(int i = 0;i<n;i++) {
    BuyerName = arrayNames[i];
        for(int j = 0;j<c;j++){
            if(MaxPrice < arrayPrices[j][i] || MaxPrice == arrayPrices[j][i]){
                MaxPrice = arrayPrices[j][i];
            }
        }
        System.out.println(i + " product highest price was " + MaxPrice + "Buyer was: " + BuyerName );
        MaxPrice = 0.0f;
    }   

}

}

1 个答案:

答案 0 :(得分:0)

这可能对您有所帮助

    String BuyerName;
    float MaxPrice = 0.0f;

    int mostExpensiveBuyer =-1;
    for(int i = 0;i<n;i++) {
        BuyerName = arrayNames[i];
        for(int j = 0;j<c;j++){
            if(MaxPrice < arrayPrices[j][i] || MaxPrice == arrayPrices[j][i]){
                MaxPrice = arrayPrices[j][i];
                mostExpensiveBuyer = j;
            }
        }

        MaxPrice = 0.0f;
    }
    System.out.println("Buyer with the most expensive product is " + arrayNames[mostExpensiveBuyer]);