gpt4 book ai didi

java - 如何从 LinkedList 获取数据?

转载 作者:行者123 更新时间:2023-11-29 05:55:28 25 4
gpt4 key购买 nike

这是我正在为我的程序寻找的示例输出。

示例输出

On each line enter a stadium name and the game revenue

Enter done when you are finished

Giants 1000

Foxboro 500

Giants 1500

done

Enter the name of a stadium to get the total revenue for:

Giants

The total revenue is 2500.00

除了最后的总收入,我的一切都正常了。我不确定如何进入我的链表并获取游戏收入并显示它。这是我现在的代码,以及我一直在搞乱的东西......

import java.util.LinkedList;
import java.util.Scanner;


public class LinkedLists {

private final Scanner keyboard;



private final LinkedList<String> stadiumNames;
private final LinkedList<Integer> gameRevenue;


public LinkedLists() {
this.keyboard = new Scanner(System.in);
this.stadiumNames = new LinkedList<String>();
this.gameRevenue = new LinkedList<Integer>();
}

public void addData(String stadium, int revenue){
stadiumNames.add(stadium);
gameRevenue.add(revenue);
}

public void loadDataFromUser() {
System.out.println("On each line enter the stadium name and game revenue.");
System.out.println("Enter done when you are finished.");

boolean done = false;
while(!done) {
System.out.print("Enter the name of the stadium:");
String stadium = keyboard.next();
if (stadium.equals("done")) {
done = true;
} else {
System.out.print("Enter game revenue: ");
addData(stadium, keyboard.nextInt());
}
}
}

// return -1 if not found
public int getIndexForName(String name) {

if(stadiumNames.contains(name)){
System.out.println("The total revenue is: " +gameRevenue.get(0));
System.exit(0);
}

return -1;

}


public void showInfoForName(String name) {
int index = getIndexForName(name);
if (index==-1) {
System.out.println("There is no stadium named " + name);
} else {

}
}

public void showInfoForName() {
System.out.println("Enter the name of the stadium to get the total revenue for it.");
showInfoForName(keyboard.next());
}

public static void main(String[] args) {
LinkedLists pgm = new LinkedLists();
pgm.loadDataFromUser();
pgm.showInfoForName();
}
}

最佳答案

试试这个:

public int getIndexForName(String name) {
if (stadiumNames.contains(name)) {
int total = 0;
for (int i = 0 ; i < stadiumNames.size() ; i++)
if (stadiumNames.get(i).equals(name))
total += gameRevenue.get(i);
System.out.println("The total revenue is: " + total);
System.exit(0);
}
return -1;
}

虽然有更好的方法可以做到这一点。我也许会使用 <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Map.html" rel="noreferrer noopener nofollow">Map</a>将每个体育场名称映射到其总收入。您可以在 addData 中更新此 map 方法。

关于java - 如何从 LinkedList 获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12333721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com