超市希望奖励当天的顶级客户,即拥有最大销售额的topN客户,其中topN是该计划用户提供的价值,在超市的屏幕上显示客户的名字。为此,客户的购买金额存储在ArrayList中
实现方法:public static ArrayList
编写一个程序,提示收银员输入所有价格和名称,将它们添加到两个数组列表中,调用您实现的方法,并显示结果。使用0的价格作为哨兵。
编译时的错误是:
------ Compile ----------
hw1num2.java:44: error: cannot find symbol
double check = iter.nextDouble();
^
symbol: method nextDouble()
location: variable iter of type Iterator
hw1num2.java:45: error: cannot find symbol
if (check>=sorted(topN-1))
^
symbol: method sorted(int)
location: class hw1num2
hw1num2.java:47: error: no suitable method found for add(double)
topCust.add(check);
^
method ArrayList.add(int,String) is not applicable
(actual and formal argument lists differ in length)
method ArrayList.add(String) is not applicable
(actual argument double cannot be converted to String by method invocatio>n conversion)
3 errors
Output completed (1 sec consumed) - Normal Termination
这就是我所拥有的:
import java.util.*;
public class hw1num2
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList<Double> sales = new ArrayList<Double>();
ArrayList<String> customers = new ArrayList<String>();
boolean end = true;
while (end) //Continues to take input for customer names and purchases until done
{
System.out.println("Enter the first name of the customer.");
String cust = in.next();
System.out.println("Enter the purchase total of that customer.");
Double total = in.nextDouble();
sales.add(total);
customers.add(cust);
System.out.println("Enter 1 if you have another customer to add, or 2 if you are done.");
int choice = in.nextInt();
if (choice != 1)
{
end=false;
}
}
System.out.println("How many top customers would you like to display?");
int topN = in.nextInt();
System.out.println(nameOfBestCustomers(sales, customers, topN)); //calls method that computes top custs
}
public static ArrayList<String> nameOfBestCustomers(ArrayList<Double> sales, ArrayList<String> customers,
int topN) //Finds out who the topN customers were
{
ArrayList<Double> sorted = new ArrayList<Double>(sales); //create copy of sales ArrayList
ArrayList<String> topCust = new ArrayList<String>(); //create ArrayList to hold top cust names
Collections.sort(sorted); //sort the copied ArrayList.
Iterator iter = sales.iterator();
while (iter.hasNext()) //iterate through sales ArrayList to find indexes of top purchases
{
for (int i=0;i<sales.size();i++)
{
double check = (double)iter.next();
if (check>=sorted.get(topN-1)) //checks if each index is >= the top Nth customer
{
topCust.add(customers.get(i)); //if so, adds it to topCust list
}
}
}
return topCust; //returns the list with the top customer names
}
}
答案 0 :(得分:1)
1-您收到错误,因为Iterator类没有名为nextDouble()的方法。 请查看Iterator API以获取支持的方法列表。
2- topCust是一个String ArrayList,你不能直接在该列表中添加一个double。
3- P:S:你的代码在这里:
int choice = 1;
if (choice != 1)
{
end=false;
}
会在主方法中导致无限循环。
希望这有帮助。