gpt4 book ai didi

java - 尝试对 ArrayList 使用 for 循环时出现 .length 错误

转载 作者:行者123 更新时间:2023-12-01 18:33:37 25 4
gpt4 key购买 nike

首先,我对这个标题感到抱歉,我想不出更好的措辞方式。实际的错误在于选项 3(每当我尝试将选项 1 中的所有销售额加在一起时)。当我尝试使用 salesList.length 跟踪数组的大小时,我得到 cannot find symbol-variable 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);
}
}

最佳答案

将其更改为salesList.size();。与数组不同,ArrayList 的长度不是可直接访问的字段。

关于java - 尝试对 ArrayList 使用 for 循环时出现 .length 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23032477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com