简体   繁体   中英

Returning multiple values of arrayList

I have a method that needs to display history of bids entered into the system and what I have right now for the method is:

@Override
public String displayHistory() {
    String bidder = toString();
    if (this.bids.isEmpty()) {
        return bidder + " = no bids";
    }
    for (int i = 0; i < this.bids.size(); i++) {
        bidder = "\n" + this.bids.get(i).toString() + "\n";
    }
    return toString() + " = " + bidder;
}

toString method: (correct)

@Override
public String toString() {
    return this.productId + ": " + this.productName;
}

What I need to the method to do is to print out in a form that passes my test class:

Test class code:

assertEquals("1: teddy = \n"+"J***e bid £7.0\n"+"S***a bid £5.0\n",product1.displayHistory());  

1: teddy = \\n J***e bid £7.00 \\n S***a bid $5.00 \\n

but currently my method is printing this:

1: teddy = \\n J***e bid £7.00 \\n blank \\n

however when I debug the program and check the array list at this point the second bid is inside but no displaying with the for loop.

is there a way in which I can change this loop so that it print out all of the values of the array list in this and not just the last value that was entered into the list? I assume it has to use a looping system but maybe not? Any help will be greatly appreciated.

In your loop:

for (int i = 0; i < this.bids.size(); i++) {
    bidder = "\n" + this.bids.get(i).toString() + "\n";
}

you assign each time the current one bid to bidder variable. Instead, you should add like bidder += ... but concating a String is better yo do by StringBuilder.append()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM