2014-04-12 40 views
0

首先我對標題感到抱歉,我想不出一個更好的方式來表達它。實際的錯誤在選項3中(每當我嘗試將選項1中的所有銷售加在一起)。當我嘗試使用salesList.length來跟蹤數組的大小時,我得到了cannot find symbol- variable length我很新使用數組列表,並且該方法在較早的數組中工作,但該數組不是動態的。有沒有一種特定的方式來跟蹤動態數組列表的長度?。嘗試對ArrayList使用for循環時出現.length錯誤

import java.util.*; 
public class CustomerTest 
{ 
public static void main(String[] args) 
     { 
      double totalSales = 0; 
      ArrayList<String> nameList; 
      nameList = new ArrayList<String>(); 
      ArrayList<Double> salesList; 
      salesList = new ArrayList<Double>(); 
      Scanner myScanner = new Scanner(System.in); 
      boolean done = true;  
      do 
      { 

       System.out.println("1) Add a new customer \n 2) Print all customers \n 3) Compute and print the total sales \n 4) Quit"); 
       int choice = Integer.parseInt(myScanner.nextLine()); 
       if (choice == 1) 
       { 
        System.out.print("Add a new customer "); 
        String answer = myScanner.nextLine(); 
        nameList.add(answer); 
        System.out.print("Enter their sales "); 
        String answer2 = myScanner.nextLine(); 
        double answer3 = Double.parseDouble(answer2); 
        salesList.add(answer3); 
       } 
       else if(choice == 2) 
       { 
        System.out.println("Customers: " + nameList); 
        System.out.println("Sales: " + salesList); 
       } 
       else if(choice == 3) 
       { 
        for(int i = 0; i < salesList.length; i++) 
        { 
        totalSales = totalSales + salesList[i]; 
        } 
        System.out.println(totalSales); 
       } 
       else if(choice == 4) 
       { 
        System.out.println("Goodbye *Bows gracefully*"); 
        done = false; 
       } 
       else 
        System.out.println("Invalid Choice");  
      } 
      while (done); 
      System.exit(0); 
     } 
} 

回答

1

將其更改爲salesList.size();。與數組不同,ArrayList的長度不是可直接訪問的字段。

+0

@ user3451158肯定。 – Azar

1

陣列具有length字段

ArrayList多年平均值有長度字段類型使用size()

1
else if (choice == 3) { 
     for (int i = 0; i < salesList.size(); i++) { 
      totalSales += salesList.get(i); 
     } 
     System.out.println(totalSales); 
     } 

用這個替換選擇3,它應該工作。

0

您的代碼存在錯誤:將else if(choice==3) {}條件部分更改爲following。你不能使用salesList.length,它可以使用salesList.size()進行,並懇求改變salesList[i] to salesList.get(i).

else if(choice == 3) 
       { 
        for(int i = 0; i < salesList.size(); i++) 
        { 
        totalSales += salesList.get(i); 
        } 
        System.out.println(totalSales); 
       } 
+0

請教他使用'+ ='! – CodeCamper

+0

謝謝!編輯。 –