所以我有两个类,一个使用toString方法,我需要打印一个字段作为日期和时间,但我很难做到这一点。这是我的电子邮件类(基本字段,构造函数,getter和setter:
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Comparator;
import java.util.Date;
public class Email {
private String to;
private String cc;
private String bcc;
private String subject;
private String body;
private GregorianCalendar timestamp; //time that email was created
public Email(String to, String cc, String bcc, String subject, String body) {
super();
this.to = to;
this.cc = cc;
this.bcc = bcc;
this.subject = subject;
this.body = body;
timestamp = (GregorianCalendar) new GregorianCalendar().getInstance();
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getCc() {
return cc;
}
public void setCc(String cc) {
this.cc = cc;
}
public String getBcc() {
return bcc;
}
public void setBcc(String bcc) {
this.bcc = bcc;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public Date getTimestamp() {
return timestamp.getTime();
}
public void setTimestamp(GregorianCalendar timestamp) {
this.timestamp = timestamp;
}
这是我的Folder类,其中包含Email对象。除了这种方法之外,我只采用了以下方法:
import java.sql.Timestamp;
import java.util.*;
public class Folder implements Comparable{
private ArrayList<Email> emails;
private String name;
private String currentSortingMethod;
//constructors, getters, setters and other methods omitted
public String toString(){
String a = "";
int j = 1;
for(int i = 0; i < emails.size(); i++){
String k = Integer.toString(j);
a += String.format("%-8s %-5s %-8s %-1s %10s", " "+ k +" ", "|" , emails.get(i).getTimestamp(), "|", emails.get(i).getSubject()+ " \n");
j = Integer.parseInt(k);
j++;
}
return(String.format("%-8s %-5s %-8s %-1s %10s", "Index", "|", "Time", "|", " Subject") + "\n" + "-------------------------------------\n" + a);
}
toString方法应该打印像这样的东西
Index | Time | Subject
-------------------------------------
1 | Time | e
2 | Time | d
3 | Time | c
4 | Time | b
5 | Time | a
它适用于其他领域,但我需要&#34;时间&#34;要填充该电子邮件对象创建时间戳的列。 示例:12/38 PM 4/8/2012
非常感谢您的帮助!
答案 0 :(得分:1)
我在本地运行它并且它有效..见下文。你在时间戳字段中得到了什么?
Index | Time | Subject
-------------------------------------
1 | Fri Aug 12 18:16:59 PDT 2016 | subject
2 | Fri Aug 12 18:17:00 PDT 2016 | subject