简体   繁体   English

在Java中打印出数组元素的数据

[英]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? 如果我有一个类类型(汽车)的数组,并且已使用set方法为每辆汽车指定了品牌和型号,那么如何打印出特定元素的品牌和型号? 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 您需要在类中添加toString()方法

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());
          }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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