Nim*_*nim 6 java iterator data-structures
我有一个投资组合类,也有投资类的链表(例如 - 谷歌是投资的一个实例),每个投资都有一个交易历史(另一个链表),每个交易的数据.
当用户想要进行交易(以5K购买谷歌股票)时,我需要找出投资(在谷歌中)是否已经存在于投资列表中.如果没有 - 添加新的投资(并为其交易历史添加交易),如果确实如此 - 只需添加另一个链接到谷歌的tradeHistory链表.
问题 - 我需要findInvestment方法从投资列表返回对谷歌(投资实例)的引用,以便我可以更新其交易历史.该方法返回一个listIterator而不是对investmentList中的位置的引用(应该是投资类).我该如何纠正findInvestment?(发现= iter错了)
public class Portfolio {
private LinkedList<Investment> investmentsList;
public Portfolio() {
investmentsList = new LinkedList<Investment>();
}
public void addInvestment(String symbol, double money){
Investment invest = findInvestment(symbol);
if (invest == null) {
System.out.println("symbol does not exist");
getInvestmentsList().add(new Investment(symbol,money));
System.out.println("New invetment has been added to your portfolio - " +symbol);
} else {
invest.addTrade(symbol,money);
System.out.println("A new trade has been added to the current investment - " + symbol);
}
}
public Investment findInvestment(String symbol){
Investment found = null;
ListIterator<Investment> iter = investmentsList.listIterator();
while (iter.hasNext()) {
if (iter.next().getSymbol().equals(symbol)) {
found = iter;
return found;
System.out.println("Found the symbol");
}
}
return found;
}
Run Code Online (Sandbox Code Playgroud)
您已经在代码中回答了您的问题!
if (iter.next().getSymbol().equals(symbol)) {
found = iter;
Run Code Online (Sandbox Code Playgroud)
看?
您正在调用 iter.next() ,它会为您提供您正在寻找的内容!因此,您只需在循环中重新编写代码,例如:
Investment currentInvestment = iter.next();
if (currentInvestment.get...) {
found = currentInvestment;
println...
return found;
}
Run Code Online (Sandbox Code Playgroud)
对于未来:请阅读您正在处理的类的 javadoc。他们通常会告诉您您需要知道的一切!提示没有。2: return 语句后面有 println 是没有意义的。
我倾向于说:让一些有经验的人审查你的代码。它不是越野车;但还有很多地方可以改进;就像你对货币使用 double (这总是一个可怕的主意);或者您的投资“模型”……可以归结为表示其“符号”的字符串。这实在是太“低级”了。