简体   繁体   中英

printing out data of array element in java

If I have an array of a class type (cars) and each car has been given a make and model using set methods, how can I then print out the make and model of a particular element? I need to print this out in a separate class

public class Car {   

    private String make;
    private String model;

    public void setMake (String str1) {

        make = str1;

    }

    public void setModel (String str2) {

        model = str2;

    }

You need to add a toString() method to your class

public class Car {   

    private String make;
    private String model;

    public void setMake (String str1) {

        make = str1;

    }

    public void setModel (String str2) {

        model = str2;

    }

    @Override
    public String toString() {
         return "Make  :"+ make + "  Model :" + model;
    }

}

Just printing a car

You can then use this as follows

public static void main(String[] args){
   Car car=new Car();
   car.setMake("Audi");
   car.setModel("ModelName");

   System.out.println(car);
}

Printing all of an array

Equally if this exists in an array of cars (I'm using the constructor I introduce in the notes for brevity)

public static void main(String[] args){
   Car[] cars=new Car[3];
   cars[0]=new Car("Audi","ModelName");
   cars[1]=new Car("BMW","ModelName");
   cars[2]=new Car("Honda","ModelName");

   for(int i=0;i<cars.length;i++){
      System.out.println(cars[i]);
   }
}

Printing after user selects an index

   public static void main(String[] args){
        Car[] cars=new Car[3];
        cars[0]=new Car("Audi","ModelName");
        cars[1]=new Car("BMW","ModelName");
        cars[2]=new Car("Honda","ModelName");

        Scanner scan=new Scanner(System.in);
        System.out.println("Select index to print, should be between 0 and " + (cars.length-1));

        //checks that user actually inputs an integer, 
        //checking its in range is left as an excercise
        while (scan.hasNextInt()==false){
            scan.next(); //consume bad input
            System.out.println("Select index to print, should be between 0 and " + (cars.length-1));

        }
        int index=scan.nextInt();

        System.out.println(cars[index]);


    }

Notes

It seems like the make and model are essential to the workings of the car class, consider changing your constructor to take them as arguments

public Car(String make, String model){
    this.make=make;
    this.model=model;
}

All this assumes you already have the element you wish to print

class Car{

    String make ;
    String model;


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

List<Car> list= new ArrayList<Car>();

Car c1=new Car();
Car c2=new Car();
Car c3=new Car();
Car c4=new Car();
list.add(c1);
list.add(c2);
list.add(c3);
list.add(c4);

for(Car car : list)
{
    System.out.println(car);    
}

Try this

private static String toString(sample[] carTypes)
    {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < carTypes.length; i++)
        {
            if (carTypes[i] != null)
            {
                stringBuilder.append(" Name : ");
                stringBuilder.append(carTypes[i].name);
                stringBuilder.append(",");
                stringBuilder.append(" Model : ");
                stringBuilder.append(carTypes[i].model);
                stringBuilder.append(",");
            }
        }
        return stringBuilder.toString().substring(0, stringBuilder.toString().length() - 1);
    }

output :

Name : BMW, Model : Mark 3, Name : AUDI, Model : A-6, Name : BENZ, Model : BZ
public class Car {   

    private String make;
    private String model;

    public Car(String make, String model) {
       this.make = make;
       this.model = model;
    }

    public void setMake (String str1) {

        make = str1;

    }

    public void setModel (String str2) {

        model = str2;

    }

    public String getMake() {
      return make;
    }

    public String getModel() {
      return model;
    }
}

public class PrintCars {
   public static void main(String []args) {

          Car cars[] = new Car[10];
          // Assume you populate the array with Car objects here by code
          cars[0] = new Car("make1", "model1");
          for (Car carObj : cars) {
            System.out.println(carObj.getmake());
            System.out.println(carObj.getmodel());
          }
    }
}

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