超市想要奖励每天最好的顾客,在超市的屏幕上显示顾客的名字 . 为此,客户的购买金额存储在ArrayList中,客户的名称存储在相应的ArrayList中 . 实现一个方法public static String nameOfBestCustomer(ArrayList sales,ArrayList customers),它返回具有最大销售额的客户的名称 . 编写一个程序,提示收银员输入所有价格和名称,将它们添加到两个数组列表,调用您实现的方法,并显示结果 . 使用0的价格作为哨兵 .
到目前为止,我在使用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();
}
}
}
2 回答
你的错误在这里:
如果用户输入的num大于1,则此循环将立即终止 . 想要它是:
您还添加了错误的数据 . 而不是这个:
和
做,
和
你在这里有2个错误我在下面纠正了它们
首先你的for循环应该按照我提出的方式进行格式化,否则它总是立即结束,除非只有1个客户,并且你使用的
.add()
方法自动添加内部到数组列表末尾的内容 .