gpt4 book ai didi

java - 如何在java中打印对象数组

转载 作者:行者123 更新时间:2023-11-30 12:06:44 32 4
gpt4 key购买 nike

假设有一个名为 Product 的类,它有两个名为 p1 和 p2 的产品对象,它们具有以下字段:

P1--> int productId =123, String name ="iPhoneS8", int unitPrice =1000, String datMfs ="12/18/2017". P2--> int productId =124, String name ="Samsung Galaxy S8", int unitPrice =1200, String datMfs ="05/22/2016".

第一个问题是

1), Write a java code for the product including getters and setters methods, any three overloaded constructors including default. My solution code is the following.

class Product {
Product() {//default Constractor

}

Product(int price) {//Overloaded Constractor1

}

Product(String name) {//Overloaded Constractor2

}

Product(String name, double pri) {//Overloaded Constractor3

}

Product(int name, double pri) {//Overloaded Constractor4

}
// The following is the product fields

private int productId;
private String name;
private int unitPrice;
private String dateMdft;
//The following is getters and setters

public int getproductId() {
return productId;
}

public void setProductId(int productId) {
this.productId = productId;
}

public String getproductName() {
return name;
}

public void setProductname(String name) {
this.name = name;
}

public int getproductunitPrice() {
return unitPrice;
}

public void setUnitPrice(int unitPrice) {
this.unitPrice = unitPrice;
}

public int getUnitPrice() {
return unitPrice;
}

public void setDateMan(String dateMdft) {
this.dateMdft = dateMdft;
}

public String getDateManftd(String dateMdft) {
return dateMdft;
}

第二个问题是

2), Write a method called printOutedDatedProduct(from the above) and iterate through the object and print out the data for only the outdated product to the screen in CSV format. the method should print 124, Samsung Galaxy S8,1200, 5/22/2016.

我真的很努力编写方法并打印出过时的产品,所以如果有人帮助我,我真的很感谢社区,就第一个问题的解决方案而言,我也非常愿意接受任何评论。非常感谢!

最佳答案

我建议将日期存储在 LocalDate 对象中。为什么选择 LocalDate?这是一个编写良好且经过测试的日期维护类。如何实例化和比较:

LocalDate d1 = LocalDate.of(2000, 06, 26);//YYYY-MM-DD
LocalDate d2 = LocalDate.now();

System.out.println(d1.compareTo(d2));//if d1 < d2, returns negative integer (difference between dates), otherwise positive integer.

什么是d1.compareTo(d2)?它返回一个表示日期之间差异的整数。它采用不匹配的日期的第一项,并从第一项中减去第二项。例如:2019-03-14与现在(2019-03-29)相比将返回14-29 = -15

您需要为 Product 实例的每个 LocalDate 字段调用 compareTo(LocalDate) 方法,并与 LocalDate.now(); 进行比较。当数字为负数时,打印有关产品的信息。

关于java - 如何在java中打印对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55350104/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com