使用增强的for-loop从两个ArrayLists中检索数据 [英] Using enhanced for-loop to retrieve data from two ArrayLists
问题描述
代码的思想是列出所有的客户,与他们的帐户,如下面的例子:
客户1
帐户1余额
帐户2余额
客户2
帐户3余额
帐户4余额
..等等。
问题在于,使用的代码(如下所示)与第一个客户所使用的代码一样,显示了所有的帐户。但它停在那里。所以客户2将不会被打印出来,尽管存在于数据库中。
public String allAccounts(){
for (客户客户:客户){
String clientInfo =;
clientInfo = clientInfo + customer.getCust()+\\\
\\\
; (账户:customer.accounts)
{
clientInfo = clientInfo + account.getAccinfo()+\\\
;
}
返回clientInfo;
}
返回未使用;
我可能会添加customer.getCust获取客户的名称,那account.getAccinfo得到帐号和余额的帐户。而且,因为它为第一个客户inteneded,我想这是一个循环问题,而不是功能本身。
任何帮助将不胜感激。
编辑:非常感谢所有人的快速和良好的答案!非常感谢!
解决方案
init a StringBuilder $ c $例如(Customer ...
循环,
更改以外的 sb
return clientInfo
转换为 sb.append(clientInfo)
replace returnNot in use
with return sb.toString()。length == 0?Not in use:sb.toString();
I have a question about a (probably very) simple problem I've encountered in the code included.
The idea of the code is to list all customers, with their accounts, like my example below:
Customer 1
Account 1 balance
Account 2 balance
Customer 2
Account 3 balance
Account 4 balance
..and so on.
The problem is that the code used (shown below) works like intended with the first customer, showing all of it's accounts. But it stops there. So Customer 2 won't be printed out despite existing in the database.
public String allAccounts() {
for (Customer customer : clients) {
String clientInfo = "";
clientInfo = clientInfo + customer.getCust() + "\n\n";
for (Account account : customer.accounts) {
clientInfo = clientInfo + account.getAccinfo() + "\n";
}
return clientInfo;
}
return "Not in use";
}
I might add that the customer.getCust gets the name of the customer, and that account.getAccinfo gets the account-number and balance of the account. And since it works as inteneded for the first customer I suppose it's a problem with the loop rather than the functions themselves.
Any help would be much appreciated.
Edit: Thanks a lot everybody for quick and good answers! Very much appreciated!
解决方案
- init a
StringBuilder
E.g. sb
outside the for(Customer ...
loop,
- change the
return clientInfo
into sb.append(clientInfo)
- replace
return "Not in use"
with return sb.toString().length==0?"Not in use": sb.toString();
这篇关于使用增强的for-loop从两个ArrayLists中检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!