[英]Why does the code print the statement twice, but differently?
我的问题陈述是:
编写一个程序来创建泛型类 LinkedList 的两个实例。
第一个实例是 StadiumNames,将保存 String 类型的项目。
第二个实例是 gameRevenue,将保存 Double 类型的项目。
在一个循环中,读取一个赛季中进行的球类运动的数据。
一场比赛的数据包括体育场名称和为那场比赛赚到的钱。
将比赛数据添加到 StadiumNames 和 gameRevenue。
由于可以在特定体育场进行不止一场比赛,因此 StadiumNames 可能有重复的条目。
读取所有比赛的数据后,读取体育场名称并显示该体育场所有比赛的总收入。
我试图从用户那里获取每个输入,然后将每个输入加在一起并得到它的总和,它起初似乎是正确的,但随后它打印了另一个完全不同的数量。 这是为什么? 任何帮助表示赞赏。
每个输入的stadiumName
和gameRevenue
都被添加到一个linkedList
。
请注意,我已经编写了两个链表,但它不允许我发布大量代码。 谢谢你。
boolean Data = true;
while (Data) {
stadiumNames.add(name);
gameRevenue.add(rev);
System.out.println("Do you want another game? ");
String yesorno = scan.next();
if (yesorno.equals("No"))
break;
else {
if (yesorno.equals("yes"))
System.out.println("Enter stadium name: ");
name = scan.next();
System.out.println("Enter amount of money for the game: ");
rev = scan.nextDouble();
for (int i = 0; i < stadiumNames.size(); i++) {
if (stadiumNames.get(i).equals(name)) {
rev += gameRevenue.get(i);
System.out.println("The total amount of money for " + name + " is " + rev);
}
}
}
}
如果您想在用户输入数据时打印运行总计,应为每次计算重置total
。
while (true) {
System.out.println("Do you want another game? ");
String yesorno = scan.next();
if (yesorno.equals("No"))
break; // else not needed
System.out.println("Enter stadium name: ");
name = scan.next();
System.out.println("Enter amount of money for the game: ");
rev = scan.nextDouble();
stadiumNames.add(name);
gameRevenue.add(rev);
double total = 0.0;
// recalculating the total for the last stadium
for (int i = 0; i < stadiumNames.size(); i++) {
if (stadiumNames.get(i).equals(name)) {
total += gameRevenue.get(i);
}
}
System.out.println("The total amount of money for " + name + " is " + total);
}
但是,可能需要计算多个不同体育场的总数,并且需要在while
循环之后为此创建和填充地图。
使用Map::merge
函数来累积每个体育场名称的总数很方便。
Map<String, Double> totals = new LinkedHashMap<>();
for (int i = 0; i < stadiumNames.size(); i++) {
totals.merge(stadiumNames.get(i), gameRevenue.get(i), Double::sum);
}
totals.forEach((stad, sum) -> System.out.println("The total amount of money for " + stad + " is " + sum));
旁白评论:不建议使用double
进行财务计算,因为浮点数学不精确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.