[英]Print from array list
我需要能夠打印出從陣列列表中獲得貸款的所有學生。
意味着所有學生的金額都超過0。
我已經可以打印所有學生和他們擁有多少...但我不知道如何讓它只打印貸款學生。
這是當前的代碼
刪除個人原因
我假設StudentLoan
有一個字段public int loanAmount
那么你可以這樣做:
for(StudentLoan loan : loans) {
int index=0;
if (loans.loanAmount > 0) {
System.out.print(index + " : ");
loan.printDetails();
index++;
}
}
這樣只打印loanAmount > 0
貸款。
如果字段loanAmount
是private
您可以簡單地為該字段實現getter方法並將條件更改為:
if (loan.getloanAmount() > 0) {
編輯
從評論中回答你的問題:
要刪除所有loamAmount
為0的貸款,我們只需為每個循環添加另一個if
:
for(StudentLoan loan : loans) {
int index=0;
// print loans with amount > 0
if (loan.loanAmount > 0) {
System.out.print(index + " : ");
loan.printDetails();
index++;
}
// delete loans with amount = 0
if (loan.loanAmount == 0) {
loans.remove(loan) // UNSAFE! see edit below
}
}
編輯
在迭代集合時使用.remove
是不安全的。 它應該使用像這樣的iterator
:
import java.util.Iterator // add to imports
Iterator<StudentLoan> i = loans.iterator();
while (i.hasNext()) {
StudentLoan loan = i.next();
if (loan.getAmount() == 0) {
i.remove();
}
}
我猜你在StudentLoan對象中有變量Amount的getter,即getAmount()。 如果沒有,你應該創建一個。
打印方法將更改為:
public void printLoanDitails()
{
System.out.println("Loan Summery: ");
int index=0; //This should be outside the loop, or it will be set to 0 each time
for(StudentLoan loans : loan) {
if(loans.getAmount() > 0)
{
System.out.print(index + " : ");
loans.printDetails();
index++;
}
}
System.out.println();
}
您應該將此邏輯添加到PayOff方法中。
如果沒有看到你的studnetLoan類,就不能確定你在使用print語句做什么
你有:
for(StudentLoan loans : loan) {
int index=0;
System.out.print(index + " : ");
loans.printDetails();
index++;
}
我會做更像這樣的事情:
for(StudentLoan loan : loanList) {
if(loan.getAmount() > 0)
loan.printDetails();
}
請注意,我已將貸款列表命名為“loanList”,或者它可能是“貸款”,但將其稱為“貸款”是沒有意義的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.