简体   繁体   中英

How do I make it to where Boat object removee only prints out the recent added item to “removed” Array

removed is an array that contains a list of boat objects but I want it to print the boat object that was just added instead of the whole removed array list.

Any way to do this?

public void removedLog() {

    // for each boat in this log
    for (int i = 0; i < removed.size(); i++) {

        Boat removee = removed.get(i);


        // print boat info and where it is.
        System.out.printf("%8s%10s%10s%10s      $%.6s%n%n", removee.getName().toUpperCase(),
                "REMOVED", removee.getGasAmount().toUpperCase(), removee.getIceAmount().toUpperCase(), removee.getPrice());
    }
}

I think its better to use ArrayList for this. So you can get the last inserted item like as follows,

 Boat removee = arrayList.get(arrayList.size() - 1);

Edited

Import

import java.util.ArrayList;

Create ArrayList

ArrayList<Boat> arrayList =  new ArrayList<Boat>();

Add boat objects to array list

arrayList.Add(new Boat());

If you cant avoid the loop, you can try this. Declare the Boat removee outside the loop, and move the print statement to after the loop.

If you can avoid the loop, you should try the solution from Saveendra Ekanayake .

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