如何使用对象打印arraylist

时间:2019-01-12 23:01:31

标签: java arraylist printing

我正在尝试打印一个包含不同对象的arraylist,但是我做不到,因为我对java很陌生。

这是我的代码:

这是我尝试过的。

class ST {
    String name;
    String email;
    int code;



    //constructor
    public ST(String name, String email, int code) {
        this.name = name;
        this.email = email;
        this.code = codeSequence.incrementAndGet();  //Atomically increments by one the current value.
    }



    //getters +setters



}



//the main class
public class JavaApplication1 extends ST{


    static ArrayList<ST> array = new ArrayList <ST>();   //T for Ticket( Generic Type)
    static AtomicInteger codeSequence = new AtomicInteger();  //Creates a new AtomicInteger with initial value 0




 public JavaApplication1(String name, String email, int code){
      super(name, email, code);           

 }  



 public static void main(String[] args){
Scanner reader = new Scanner(System.in);
int code;

int readcode1=0;
JavaApplication1 ticket2 = new JavaApplication1();
ticket2. Person3();

JavaApplication1 ticket1 = new JavaApplication1();
ticket1. Person3();

System.out.println("You want to renew your ticket, so type the code of the ticket. ");
readcode1 = reader.nextInt();  //reads what the user has typed
for (int i = 0; i < array.size(); i++) {
    if (i == readcode1){

    System.out.println(array.get(i));

    }
}

}
//private Object input;
       void Person3( ){    //+SAVE email, name

        Scanner input = new Scanner(System.in);
        System.out.println("Type your full name.");
        String name = input.nextLine();
        System.out.println("Please type your email. ");
        String email = input.nextLine();

        int code = codeSequence.incrementAndGet();
        System.out.println("Your code is:"+code);         

        array.add(new ST( "name", "email", code));



       }      

它是打印出来的:

运行: 输入您的全名。 esdf 请输入您的电子邮件。 fdsf 您的代码是:1 输入您的全名。 44 请输入您的电子邮件。 df 您的代码是:3 您要续订票证,因此输入票证代码。 1个 命名电子邮件4

我需要打印用户输入的姓名和电子邮件。要执行此操作,我需要提出什么要求?

1 个答案:

答案 0 :(得分:0)

为您的ST类创建toString()方法,然后打印

System.out.println(array.get(i).toString());

ST类中的实现

class ST {
    String name;
    String email;
    int code;



    //constructor
    public ST(String name, String email, int code) {
        this.name = name;
        this.email = email;
        this.code = codeSequence.incrementAndGet();  //Atomically increments by one the current value.
    }


    //getters +setters

    .
    .
    .

    public String toString() {
        return "Name: "+name+", Email: "+email;
    }



}