Java 我已经创建了一个自定义类,它可以获取日期和时间作为字符串,我想访问该对象并为该类设置数据
我已经创建了一个自定义类,它可以获取日期和时间作为字符串,我想访问该对象并为该类设置数据 这是我的密码Java 我已经创建了一个自定义类,它可以获取日期和时间作为字符串,我想访问该对象并为该类设置数据,java,Java,我已经创建了一个自定义类,它可以获取日期和时间作为字符串,我想访问该对象并为该类设置数据 这是我的密码 public class DateTime { private String Date; private String Time; public DateTime(String Date,String Time) { this.Date=Date; this.Time=Time; } public void showDateAndTime() { System.
public class DateTime {
private String Date;
private String Time;
public DateTime(String Date,String Time) {
this.Date=Date;
this.Time=Time;
}
public void showDateAndTime() {
System.out.println("entery Date is :");
System.out.println(Date);
System.out.println("entery time is :");
System.out.println(Time);
}
}
public class Vehicle {
public int ID;
public String Brand;
public String type;
public DateTime entryTimeDate;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Vehicle v1=new Vehicle();
v1.entryTimeDate**********
}
我想将日期时间值设置为v1 object任何建议?在
Vehicle
类中不要有public
字段,而是将它们设置为private
,然后才能访问它们。然后vehicle.getEntryTimeDate()
将足以为您提供车辆的DateTime对象。换言之:
public class Vehicle {
private int id;
public String brand;
public String type;
public DateTime entryTimeDate;
public Vehicle()
{
setId(0);
setBrand("");
setType("");
setEntryTimeDate(new DateTime("DATE", "TIME"));
}
public Vehicle(int id, String brand, String type, DateTime entryTimeDate) {
this.id = id;
this.brand = brand;
this.type = type;
this.entryTimeDate = entryTimeDate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public DateTime getEntryTimeDate() {
return entryTimeDate;
}
public void setEntryTimeDate(DateTime entryTimeDate) {
this.entryTimeDate = entryTimeDate;
}
public static class DateTime{
private String date;
private String time;
public DateTime(String date,String time) {
this.setDate(date);
this.setTime(time);
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
public static void main(String[] args) {
Vehicle v1 = new Vehicle();
v1.getEntryTimeDate().setTime("Time of the vehicle");
v1.getEntryTimeDate().setDate("Date of the vehicle.");
}
}
一些注意事项:忽略
DateTime
类中的static
关键字。我这样做是为了创造一个新的世界。还要注意我遵循的字段命名约定(驼峰大小写)。它是Java程序员最常用的命名约定。不清楚询问了什么,尝试了什么,但v1是一种工具,对吗?因此,编译器不允许在DateTime引用侧设置Vehicle对象。请尝试java.time.LocalDateTime类,这比滚动您自己的类v1.entryDateTime=new DateTime(“明天”、“现在!!!”)
或任何您想要的时间和日期值都要多。它在线程“main”中返回异常`v1.getEntryTimeDate().setTime(“车辆时间”)行中的java.lang.NullPointerException;v1.getEntryTimeDate().setDate(“车辆日期”)`@我编辑了我的文章。这确实是我的错误。我从未在默认构造函数中初始化Vehicle
的entryTimeDate
对象。因此,getEntryTimeDate
方法返回null。现在,默认构造函数初始化所有字段,避免在所有getter中使用NPE。