简体   繁体   中英

How to print Array of Object in java

Assuming there is a Class called Product which has two product object called p1 and p2 which have the following fields:

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".

The first question is

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;
    }

The second Question is

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 .

I am really Struggling to write the method and print out the outdated product so I really appreciate the community if anybody helps me and I am also really open to take any comments as far as the solution to the first question is concerned too. Great Thanks!

I would recommend to store date in LocalDate object. Why LocalDate? It is a well-written and tested class for date mainetenance. How to instantiate and compare:

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. 

What does d1.compareTo(d2) ? It returns an integer representing the difference bwtween dates. It takes the first terms of dates that don't match and subtracts the second from the first. For example: 2019-03-14 compared to now ( 2019-03-29 ) will return 14-29 = -15 .

You need to call compareTo(LocalDate) method for each LocalDate field of Product instance and compare with LocalDate.now(); . When the numer is negative, print info about the product.

Java by default calls the toString method when you try to use an object as a String then what you need to do is to prepare the Product toString method first like this below:

public String toString(){
   return productId+", "+name+", "+unitPrice+", "+dateMdft;  
}

after that, the printing is going to be easy but you need to check for the date , manipulating a date as a String will cost you a lot. you can find java dates best practices presented in a good way here

after you learned how to use the Date class and how to check your date now you all you need to write the function that loops on the array you have and checks the date and print your data.

First, think about right datatypes for fields. You can use String for date filed, but how will you compare this dates? There is powerful JDK datetime API , let's use it. I'll recommend LocaDate , as you need only date part.

Second. Your constructors shouldn't be empty or useless. You could initialize object fields in constructors. For example:

Product(String name) {
    this(name, 0);
}

Product(String name, int unitPrice) {
    this(name, unitPrice, LocalDate.now());
}

Product(String name, int unitPrice, LocalDate dateMdft) {
    this.name = name;
    this.unitPrice = unitPrice;
    this.dateMdft = dateMdft;
}

The next step is method for string representation of object. You could override toString or create another.

private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM/dd/YYYY");

@Override
public String toString() {
    return productId + "," + name + "," + unitPrice + "," + dateTimeFormatter.format(dateMdft);
}

And the last, filter and print.

public static void main(String args[]) {
    List<Product> products = new ArrayList<>();
    products.add(new Product("1", 100, LocalDate.now().minusDays(1)));
    products.add(new Product("2", 150, LocalDate.now().minusDays(2)));
    products.add(new Product("3", 250, LocalDate.now()));

    System.out.println("Via for loop:");
    for (Product p: products) {
        if (p.getDateMdft().isBefore(LocalDate.now())) {
            System.out.println(p);
        }
    }

    System.out.println("Via stream API:");
    products
            .stream()
            .filter(p -> p.getDateMdft().isBefore(LocalDate.now()))
            .forEach(System.out::println);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM