2017-10-18 29 views
0

我有作業,其中我需要與買家和產品創建二維數組。每個產品和買家都有自己的編號,例如[買方1] [產品1],[買方1] [產品2],[買方1] [產品3]等。我需要從每一欄中找到最貴的產品,以及誰買了它。我發現它打印最貴的產品的方式,但我不知道如何申報買方爲這些產品二維數組,如何找到每列最大值的所有者

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

請堅守* *命名約定**。類名以CamelCase開頭,變量和方法名以小寫字母開頭。所以你的'BuyerName'和'MaxPrice'應該被命名爲'buyerName'和'maxPrice'。正如你所看到的那樣,它突出了他們,就好像他們在哪些課上讓閱讀更難。 – Zabuza

回答

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]); 
+0

你有什麼改變?爲什麼這解決了這個問題?你能提供解釋嗎? – Zabuza

+0

我使用mostExpensivebuyer作爲最昂貴的買家索引的佔位符,直到for循環完成其工作。 – duongthaiha

相關問題