简体   繁体   中英

Java print arraylist numbered

i have this

public String toString()
{
        return "a " + year + " " +  make + " " + model +
                " with a VIN# of " + vin + " and a mileage of " + miles;
}

and this:

ArrayList<Auto> autos = new ArrayList<Auto>();

and this:

 public static void loadNewData(ArrayList<Auto> a, ArrayList<Customer> c)
    {
        a.add(new Auto(2009,"Ford" , "Mustang","ABC123", 1256.54));
        a.add(new Auto(2010,"Chevy","Camero","QWI459", 33.98));
        a.add(new Auto(1970,"Pink","Cadillac","950AKH", 212874.51));
        a.add(new Auto(2007,"Lotus","Elise MkII","1A2D3F", 12859.90));

        c.add(new Customer( "Brett Farve",false));
        c.add(new Customer( "Bruce Springsteen",true));
        c.add(new Customer( "Mickey Mouse", true));
        c.add(new Customer( "Peyton Manning", true));
        c.add(new Customer( "Donald Duck", true));
    }

i then join all that and print:

System.out.println(autos.toString());

but it comes out like this:

[a 2009 Ford Mustang with a VIN# of ABC123 and a mileage of 1256.54, a 2010 Chevy Camero with a VIN# of QWI459 and a mileage of 33.98, a 1970 Pink Cadillac with a VIN# of 950AKH and a mileage of 212874.51, a 2007 Lotus Elise MkII with a VIN# of 1A2D3F and a mileage of 12859.9]

how can i make the print to come out like this:

  1. a 2009 Ford Mustang with a VIN# of ABC123 and a mileage of 1256.54
  2. a 2010 Chevy Camero with a VIN# of QWI459 and a mileage of 33.98
  3. a 1970 Pink Cadillac with a VIN# of 950AKH and a mileage of 212874.51
  4. a 2007 Lotus Elise MkII with a VIN# of 1A2D3F and a mileage of 12859.9

Loop over your list and do a System.out.println for each entry. Something like this:

for (int i = 0; i < autos.size(); i++) {
    System.out.println((i + 1) + ". " + autos.get(i));
}

You can just add a \\r \\n to your return statement:

public String toString()
{
        return "a " + year + " " +  make + " " + model +
                " with a VIN# of " + vin + " and a mileage of " + miles + "\r \n";
}

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