2014-04-12 44 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

谢谢!编辑。 –