0

I'm reading through some coding books and am learning about classes and I want to increment the name of the class variable for months days and year.

I just want to know how to increment date more than once save its own instance variable then move to date 2.

//Class

public String month;
public int day;
public int year;

public void writer() {
    System.out.println(month+"/"+day+"/"+year);}

//Main

Scanner kb = new Scanner(System.in);

practice date1 = new practice();
practice date2 = new practice();

    System.out.println("Enter month");
        date1.month=kb.nextLine();
    System.out.println("Enter day");
        date1.day=kb.nextInt();
    System.out.println("Enter year");
        date1.year=kb.nextInt();
    kb.nextLine();
date1.writer();

    System.out.println("Enter month");
        date2.month=kb.nextLine();
    System.out.println("Enter day");
        date2.day=kb.nextInt();
    System.out.println("Enter year");
        date2.year=kb.nextInt();
date2.writer();

The Output is fine, I just don't like how much code is and I was wondering if there was a way to cut it almost in half?

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
  • 1
    Not really. Maybe some very minor stuff. – Zabuzard Aug 26 '19 at 17:32
  • Yes, you can create a `List` and create a for loop in which you create your `practice` object, ask the questions and add it to the list. That's almost your code in half literaly – Mark Aug 26 '19 at 17:33
  • 2
    "Cut in half" for what? If it results in less readable code (very likely) that will be a very heavy longer-term loss. – vonbrand Aug 26 '19 at 17:34
  • 4
    Put in a method the duplicated code – Butiri Dan Aug 26 '19 at 17:36
  • Maybe ask the user to input the date in some common format, like `05-03-2016` and then parse that into a `LocalDate` object or similar. That would result in maybe 3 lines of code but would require you to change your structure. Or you create some `parseFromDateString` method in your `practice` class to do that in the method. Note that you should stick to java naming conventions, PascalCase for class names, so `Practice`. – Zabuzard Aug 26 '19 at 17:36
  • Keep reading until you get to the section about arrays and/or lists. – Andreas Aug 26 '19 at 17:38
  • You may want to ask this in [codereview.se] instead. – Zabuzard Aug 26 '19 at 17:38
  • Just for other readers: Writing your own date class is fine practice. For production code one never would, but would use the built-in `LocalDate`. – Ole V.V. Sep 12 '19 at 06:46

0 Answers0