2014-03-13 54 views
0

超市想要獎勵每天最好的客戶,並在超市的屏幕上顯示客戶的姓名。爲此,客戶的購買金額存儲在ArrayList中,客戶的名稱存儲在相應的ArrayList中。實現一個方法public static String nameOfBestCustomer(ArrayList sales,ArrayList customers),返回具有最大銷售額的客戶的名稱。編寫一個程序,提示收銀員輸入所有價格和名稱,將它們添加到兩個數組列表中,調用您實施的方法並顯示結果。使用0作爲定點標價。使用for循環將數字添加到ArrayList中 - Java

到目前爲止,我遇到了一個問題,通過鍵盤使用for循環將數字/名稱輸入到數組中。這是我迄今爲止;

import java.util.Arrays; 
import java.util.ArrayList; 
import java.util.Scanner; 

public class TopCustomer { 

    public static String nameOfBestCustomer(ArrayList<Double> sales, ArrayList<String> customers) { 

} 

public static void main (String [] args){ 
    ArrayList<Double> sales = new ArrayList<Double>(); 
    ArrayList<String> customer = new ArrayList<String>(); 
    Scanner in = new Scanner(System.in);   
    System.out.print("How many Customers are there?"); 
    int num = in.nextInt(); 

    for (int i = 1; num <= i; i++) { 
     System.out.print("Enter name of customer " + i + ": \n"); 
     customer.add(i) = in.nextString(); 
     System.out.print("Enter how much customer " + i + ": \n"); 
     sales.add(i) = in.nextDouble(); 
    } 
} 

}

+1

使用'customer.add(in.nextString());'銷售相同。 – Braj

+0

我仍然收到錯誤:無法找到符號customer.add(in.nextString()); – Sjanes227

回答

2

您在這裏有2個錯誤我已經改正了他們下面

for (int i = 0; i < num; i++){ 
    System.out.print("Enter name of customer " + (i+1) + ": \n"); 
    customer.add(in.next()); 
    System.out.print("Enter how much customer " + (i+1) + ": \n"); 
    sales.add(in.nextDouble()); 
} 

首先你的for循環應該格式化我提出監守否則總是立刻結束的方式,除非有隻有1個客戶,你也被自動使用.add()方法添加的是內部數組列表的末尾。

+0

謝謝你的幫助!我仍然收到錯誤:無法找到符號customer.add(in.nextString()); – Sjanes227

+0

sry,我更新了這一行,嘗試使用更新 – mig

2

你的錯誤是在這裏:

for (int i = 1; num <= i; i++) { 

如果用戶超過1輸入一個NUM時,這個循環將立即終止。想要的是:

for (int i = 1; i <= num; i++) { 

你也加錯了數據。取而代之的是:

customer.add(i) = in.nextString(); 

sales.add(i) = in.nextDouble(); 

做的,

customer.add(in.nextString()) 

sales.add(in.nextDouble()); 
相關問題