英文:
Exception is occurred while trying to compare dates - Nullpointerexception and also get method is returning null value even if i have set the date
问题
在尝试比较日期时发生了空指针异常。我注意到在调试时,expectedDate
和 arrivedDate
变量的值是当前的日期时间,而我正在使用 set
方法来设置日期。请纠正我用于比较日期的代码。我的方法用于判断货物是否会按时到达、提前到达还是延迟到达。
public class ShipmentBO {
public void displayStatusOfShipment(Shipment shipment) {
Date expectedDate = new Date();
Date arrivedDate = new Date();
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Shipment s = new Shipment();
ShipmentStatus SStatus = new ShipmentStatus();
expectedDate = s.getexpectedDeliveryDate();
arrivedDate = SStatus.getarrivedDate();
String s1 = df.format(expectedDate);
String s2 = df.format(arrivedDate);
if (expectedDate.after(arrivedDate)) {
System.out.println("货物在预期日期之后到达");
} else if (expectedDate.before(arrivedDate)) {
System.out.println("货物在预期日期之前到达");
}
}
}
我在下面的主类中设置日期:
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
System.out.println("输入货物详细信息:");
String userDetail = sc.nextLine();
String userDetailParts[] = userDetail.split(",");
Shipment shipment = new Shipment();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
shipment.setid(userDetailParts[0]);
shipment.setsourcePort(userDetailParts[1]);
shipment.setdestinationPort(userDetailParts[2]);
shipment.setexpectedDeliveryDate(sdf.parse(userDetailParts[3]));
shipment.setcustomerName(userDetailParts[4]);
}
我提供的输入是以逗号分隔的 - STAJU01, 香港, 科钦, 20-05-2017, 卡迪克
Shipment 类:
import java.util.Date;
public class Shipment {
// ...(属性和方法)
}
ShipmentStatus 类:
import java.util.Date;
public class ShipmentStatus {
// ...(属性和方法)
}
注意:以上内容是翻译后的代码部分,已经排除了问题描述和要求翻译的内容之外的部分。
英文:
NUllpointerexception is occured while trying to compare dates.
I noticed that while debugging that expectedDate and arrivedDate variable value is getting current date time where as i am using set Method to set date.Please correct my code for comparing dates. My method is used to find whether the shipment will arrive on time or before expected or after expected.
public class ShipmentBO {
public void displayStatusOfShipment(Shipment shipment) {
Date expectedDate = new Date();
Date arrivedDate = new Date();
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Shipment s = new Shipment();
ShipmentStatus SStatus = new ShipmentStatus();
expectedDate = s.getexpectedDeliveryDate();
arrivedDate = SStatus.getarrivedDate();
String s1 = df.format(expectedDate);
String s2 = df.format(arrivedDate);
if (expectedDate.after(arrivedDate)) {
System.out.println("The shipment arrived after the expected date");
} else
if (expectedDate.before(arrivedDate)) {
System.out.println("The shipment arrived before the expected date");
}
}
I am setting the date in the below main class
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the shipment details :");
String userDetail = sc.nextLine();
String userDetailParts[] = userDetail.split(",");
//System.out.println(Arrays.toString(userDetailParts));
Shipment shipment = new Shipment();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
shipment.setid(userDetailParts[0]);
shipment.setsourcePort(userDetailParts[1]);
shipment.setdestinationPort(userDetailParts[2]);
shipment.setexpectedDeliveryDate(sdf.parse(userDetailParts[3]));
shipment.setcustomerName(userDetailParts[4]);
}
And the input I am giving as a comma separated - STAJU01, Hong Kong, Cochin,20-05-2017, karthick
Shipment class:
import java.util.Date;
public class Shipment {
private String id;
private String sourcePort;
private String destinationPort;
private Date expectedDeliveryDate;
private String customerName;
private ShipmentStatus[] shipmentStatus;
public String getid() {
return id;
}
public void setid(String id) {
this.id = id;
}
public String getsourcePort() {
return sourcePort;
}
public void setsourcePort(String sourcePort) {
this.sourcePort = sourcePort;
}
public String getdestinationPort() {
return destinationPort;
}
public void setdestinationPort(String destinationPort) {
this.destinationPort = destinationPort;
}
public Date getexpectedDeliveryDate() {
return expectedDeliveryDate;
}
public void setexpectedDeliveryDate(Date expectedDeliveryDate) {
this.expectedDeliveryDate = expectedDeliveryDate;
}
public String getcustomerName() {
return customerName;
}
public void setcustomerName(String customerName) {
this.customerName = customerName;
}
public Shipment() {
}
public Shipment(String id, String sourcePort, String destinationPort, Date expectedDeliveryDate,
String customerName) {
this.id = id;
this.sourcePort = sourcePort;
this.destinationPort = destinationPort;
this.expectedDeliveryDate = expectedDeliveryDate;
this.customerName = customerName;
}
public ShipmentStatus[] getShipmentStatus() {
return shipmentStatus;
}
public void setShipmentStatus(ShipmentStatus[] shipmentStatus) {
this.shipmentStatus = shipmentStatus;
}
}
ShipmentStatus:
import java.util.Date;
public class ShipmentStatus {
private String arrivalPort;
private String departurePort;
private Date arrivedDate;
private String status;
private Shipment shipment;
public Shipment getshipment() {
return shipment;
}
public void setshipment(Shipment shipment) {
this.shipment = shipment;
}
public String getarrivalPort() {
return arrivalPort;
}
public void setarrivalPort(String arrivalPort) {
this.arrivalPort = arrivalPort;
}
public String getdeparturePort() {
return departurePort;
}
public void setdeparturePort(String departurePort) {
this.departurePort = departurePort;
}
public Date getarrivedDate() {
return arrivedDate;
}
public void setarrivedDate(Date arrivedDate) {
this.arrivedDate = arrivedDate;
}
public String getstatus() {
return status;
}
public void setstatus(String status) {
this.status = status;
}
public ShipmentStatus() {
}
public ShipmentStatus(String arrivalPort, String departurePort, Date arrivedDate, String status,
Shipment shipment) {
this.arrivalPort = arrivalPort;
this.departurePort = departurePort;
this.arrivedDate = arrivedDate;
this.status = status;
this.shipment = shipment;
}
}
答案1
得分: 1
你正在对一个 new Shipment()
调用 getexpectedDeliveryDate()
方法,但我怀疑你想在接收到的参数上调用它,而参数在其他情况下保持不变。基本上,尝试将 expectedDate = s.getexpectedDeliveryDate();
修改为 expectedDate = shipment.getexpectedDeliveryDate();
。
英文:
You are calling the getexpectedDeliveryDate()
on a new Shipment()
, but I suspect you want to call it on the shipment you receive as a parameter, which you otherwise leave untouched. Basically, try changing expectedDate = s.getexpectedDeliveryDate();
to expectedDate = shipment.getexpectedDeliveryDate();
答案2
得分: 1
请看代码中的注释:
public void displayStatusOfShipment(Shipment shipment) {
Date expectedDate = shipment.getexpectedDeliveryDate();
Date arrivedDate = shipment.getShipmentStatus().getarrivedDate();
if (expectedDate.after(arrivedDate)) {
System.out.println("The shipment arrived after the expected date");
} else if (expectedDate.before(arrivedDate)) {
System.out.println("The shipment arrived before the expected date");
}
}
在Shipment类中添加一个方法,使用ShipmentStatus数组来获取货物的arrivedDate。你提到这是第三个最后的ShipmentStatus,代码可以是这样的:
class Shipment {
public Date getArrivedDate() {
if (shipmentStatus != null && shipmentStatus.length >= 3) {
return shipmentStatus[shipmentStatus.length - 3].getArrivedDate();
}
return null;
}
}
我不确定“第三个最后的状态”是否是识别正确货物状态的好方法。根据业务逻辑,更好的做法是:
- 第一个arrivedDate不为null的货物状态
- 最后一个arrivedDate不为null的货物状态
- status为'arrival'的货物状态
英文:
See comments in code:
public void displayStatusOfShipment(Shipment shipment) {
// not used:
// SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
// extract date from passed shipment instance
Date expectedDate = shipment.getexpectedDeliveryDate();
// I assume ShipmentStatus is part of Shipment so you don't need a new instance here
// ShipmentStatus SStatus = new ShipmentStatus();
// extract arrivalDate from passed shipment's ShipmentStatus:
Date arrivedDate = shipment.getShipmentStatus().getarrivedDate();
// not used :
// String s1 = df.format(expectedDate);
// String s2 = df.format(arrivedDate);
if (expectedDate.after(arrivedDate)) {
System.out.println("The shipment arrived after the expected date");
} else
if (expectedDate.before(arrivedDate)) {
System.out.println("The shipment arrived before the expected date");
}
}
In Shipment add a method which contains the logic to obtain the arrivedDate of the shipment using the ShipmentStatus array. You say it's the third last ShipmentStatus so the code can be:
class Shipment {
public Date getArrivedDate() {
if(shipmentStatus!=null && shipmentStatus.length>=3)
return shipmentStatus[shipmentStatus.length-3].getArrivedDate();
return null;
}
}
I'm not sure if the 3rd last status
is a good way to identify the right shipment status. It think it would be better to make your choice based on some business logic. For example:
* first shipment status with arrivedDate!=null
* last shipment status with arrivedDate!=null
* shipmentStatus with status='arrival'
答案3
得分: 0
get method is returning null value even if i have set the date
It's because you are not using the
Shipment
object passed todisplayStatusOfShipment(Shipment shipment)
; rather, you are creating a new instance as follows:Date expectedDate = new Date(); Shipment s=new Shipment(); expectedDate = s.getexpectedDeliveryDate();
You should replace all the above three lines with the following line:
Date expectedDate = shipment.getexpectedDeliveryDate();
Similarly, to this method, you should pass a parameter of the type,
ShipmentStatus
for the arrival date and use the same to get the arrival date i.e. you need to replace the following three lines in the similar way as shown above:Date arrivedDate = new Date(); ShipmentStatus SStatus = new ShipmentStatus(); arrivedDate = SStatus.getarrivedDate();
On comparing dates:
I had suggested you to stop using the poorly designed
java.util.Date
and to switch to the modernjava.time
API. This scenario is a perfect example for you to make that switch immediately. Let's see why:
- The modern date-time API has a class called
LocalDate
which represents just the date, i.e., it has just three fields: year, month, and day. Therefore, when you compare two instances ofLocalDate
, only these fields are compared.LocalDate
has a rich set of APIs for comparison, e.g.,LocalDate#isAfter
,LocalDate#isBefore
,LocalDate#isEqual
, etc., which compare the values of these three fields to give you the result.- You will say that
java.util.Date
also hasDate#before
,Date#after
, etc., but this is where the comparison of these methods with those of theLocalDate
ends. These methods ofjava.util.Date
compare the milliseconds sinceJanuary 1, 1970, 00:00:00 GMT
, i.e., one instance ofDate
can be before/after even with a difference of a millisecond (unlike two instances ofLocalDate
which can be before/after only with the difference in one or more of the fields: day, month, and year).public class Main { public static void main(String[] args) { Date date1 = new Date(); Date date2 = new Date(); date2.setTime(date1.getTime() - 1); System.out.println(date1); System.out.println(date2); System.out.println(date1.after(date2)); } } **Output:** Wed Aug 19 16:34:56 BST 2020 Wed Aug 19 16:34:56 BST 2020 true ## If you still insist to use `java.util.Date`: If you still insist on using `java.util.Date`, you will have to get the day, month, and year from the two instances of `Date` yourself and compare them to determine before/after cases. The choice is yours. [1]: https://stackoverflow.com/a/63267701/10819573 [2]: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#isAfter-java.time.chrono.ChronoLocalDate- [3]: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#after-java.util.Date-
英文:
> get method is returning null value even if i have set the date
It's because you are not using the Shipment
object passed to displayStatusOfShipment(Shipment shipment)
; rather, you are creating a new instance as follows:
Date expectedDate = new Date();
Shipment s=new Shipment();
expectedDate = s.getexpectedDeliveryDate();
You should replace all the above three lines with the following line:
Date expectedDate = shipment.getexpectedDeliveryDate();
Similarly, to this method, you should pass a parameter of the type, ShipmentStatus
for the arrival date and use the same to get the arrival date i.e. you need to replace the following three lines in the similar way as shown above:
Date arrivedDate = new Date();
ShipmentStatus SStatus = new ShipmentStatus();
arrivedDate = SStatus.getarrivedDate();
On comparing dates:
I had suggested you to stop using the poorly designed java.util.Date
and to switch to the modern java.time
API. This scenario is a perfect example for you to make that switch immediately. Let's see why:
-
The modern date-time API has a class called,
LocalDate
which represents just date i.e. it has just three fields: year, month and day and therefore when you compare two instances ofLocalDate
, only these fields are compared.LocalDate
has a rich set of API for comparison e.g.LocalDate#isAfter
,LocalDate#isBefore
,LocalDate#isEqual
etc. which compare the values of these three fields to give you the result. -
You will say that
java.util.Date
also hasDate#before
,Date#after
etc. but this is where the comparison of these methods with those of theLocalDate
ends. These methods ofjava.util.Date
compare the milliseconds sinceJanuary 1, 1970, 00:00:00 GMT
i.e. one instance ofDate
can be before/after even with a difference of a millisecond (unlike two instances ofLocalDate
which can be before/after only with the difference in one or more of the fields, day, month, and year).public class Main { public static void main(String[] args) { Date date1 = new Date(); Date date2 = new Date(); date2.setTime(date1.getTime() - 1); System.out.println(date1); System.out.println(date2); System.out.println(date1.after(date2)); } }
Output:
Wed Aug 19 16:34:56 BST 2020 Wed Aug 19 16:34:56 BST 2020 true
If you still insist to use java.util.Date
:
If you still insist to use java.util.Date
, you will have to get the day, month and year from the two instances of Date
yourself and compare them to determine before/after cases. The choice is yours.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论