簡體   English   中英

為什么代碼打印語句兩次,但不同?

[英]Why does the code print the statement twice, but differently?

我的問題陳述是:

編寫一個程序來創建泛型類 LinkedList 的兩個實例。
第一個實例是 StadiumNames,將保存 String 類型的項目。
第二個實例是 gameRevenue,將保存 Double 類型的項目。
在一個循環中,讀取一個賽季中進行的球類運動的數據。
一場比賽的數據包括體育場名稱和為那場比賽賺到的錢。
將比賽數據添加到 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);
            }
        }
    }
}

輸出的附加圖像

如果您想在用戶輸入數據時打印運行總計,應為每次計算重置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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM