【问题标题】:Why does the code print the statement twice, but differently?为什么代码两次打印语句,但不同?
【发布时间】:2021-12-25 13:20:17
【问题描述】:

我的问题陈述是:

编写一个创建泛型类的两个实例的程序 链表。
第一个实例是 StadiumNames,将保存以下项目 输入字符串。
第二个实例是 gameRevenue,将持有 键入双精度。
在一个循环内,读取期间进行的球类比赛的数据 一个季节。
一场比赛的数据包括一个体育场名称和 为那场比赛赚了多少钱。
将比赛数据添加到 StadiumNames 和 gameRevenue。
由于可以在特定体育场进行不止一场比赛,因此 StadiumNames 可能有重复的条目。
读取所有比赛的数据后,读取一个体育场名称并显示该体育场所有比赛的总收入。

我试图从用户那里获取每个输入,然后将每个输入加在一起并得到它的总和,一开始它似乎是正确的,但随后它打印出另一个完全不同的数量。这是为什么?任何帮助表示赞赏。

stadiumNamegameRevenue 的每个输入都添加到 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);
            }
        }
    }
}

【问题讨论】:

标签: java loops arraylist linked-list java.util.scanner


【解决方案1】:

如果您想在用户输入数据时打印运行总计,则应为每次计算重置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进行财务计算,因为floating point maths is not precise

【讨论】:

    最近更新 更多