-1

I want to write a class so that I can print the date in dd/mm format, but I have no idea to start.

Here is the main() part

Code:

import java.util.Arrays;

public class SortMonthDate {

    public static void main(String[] args) {
        MonthDate[] mdates = new MonthDate[5];
        mdates[0] = new MonthDate(22, 7);
        mdates[1] = new MonthDate(25, 8);
        mdates[2] = new MonthDate(25, 6);
        mdates[3] = new MonthDate(28, 9);
        mdates[4] = new MonthDate(5, 9);
        print(mdates);
        Arrays.sort(mdates);
        print(mdates);
    }

    static <T> void print(T[] a) {
        for (T t : a) {
            System.out.printf("%s ", t);
        }
        System.out.println();
    }
}
陈俊杰
  • 21
  • 7
  • 1
    Implement the `toString` method in your `MonthDate` class. – Seelenvirtuose Mar 16 '19 at 11:28
  • 1
    Is there a reason why you're building a custom class? – LppEdd Mar 16 '19 at 11:30
  • Welcome to Stack Overflow. In this place we’re poor at questions in the style of *I have no idea to start*, sorry. You’ve got to read the tutorials (search and you will find) about how to create a class and how to control how it prints (search for `toString`). – Ole V.V. Mar 17 '19 at 08:03
  • Possible duplicate of [How do I print my Java object without getting “SomeType@2f92e0f4”?](https://stackoverflow.com/questions/29140402/how-do-i-print-my-java-object-without-getting-sometype2f92e0f4) – Ole V.V. Mar 17 '19 at 08:05

3 Answers3

3

There's a class for that!

java.time.MonthDay

Rather than roll-your-own, use the MonthDay class built into Java 8 and later. For Java 6 & 7, use the back-port.

MonthDay[] mds = new MonthDay[5] ;
mds[0] = MonthDay.of( 7 , 22 ) ;
mds[1] = MonthDay.of( Month.AUGUST , 25 ) ;
mds[2] = MonthDay.of( Month.JUNE , 25 ) ;
mds[3] = MonthDay.of( Month.SEPTEMBER , 28 );
mds[4] = MonthDay.of( 9 , 5 ) ;
Arrays.sort(mdates);

Better to use Java Collections generally.

List< MonthDay > mds = new ArrayList<>() ;
mds.add( MonthDay.of( 7 , 22 ) ) ;
mds.add( MonthDay.of( Month.AUGUST , 25 ) ) ;
mds.add( MonthDay.of( Month.JUNE , 25 ) ) ;
mds.add( MonthDay.of( Month.SEPTEMBER , 28 ) ) ;
mds.add( MonthDay.of( 9 , 5 ) ) ;
Collections.sort( mds ) ;

Strings

I want to write a class so that I can print the date in dd/mm format,

To learn about writing the class, check out the source code in the OpenJDK project.

As for generating text representing that month-day class, simply call toString to generate a value in standard ISO 8601 format. I strongly suggest use these standard formats for logging, storing, and exchanging date-time values as text.

MonthDay.of( Month.JUNE , 25 ) )
        .toString()

--06-25

For presentation to the user, specify your desired format with DateTimeFormatter class. Search Stack Overflow for more info, as this has been covered many many times already.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM" ) ;
String output = mds.get( 0 ).format( f ) ;  // Generate string in custom format.

25/06

Dump to console.

System.out.println( "mds: " + mds ) ;
System.out.println( "mds.get( 0 ) = " +  mds.get( 0 ) + "  |  output: " + output ) ;

See this code run live at IdeOne.com.

mds: [--06-25, --07-22, --08-25, --09-05, --09-28]

mds.get( 0 ) = --06-25 | output: 25/06


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
1

If you are printing an Object to System.out Java uses the Object.toString() method to get a string representation of your Object. So you can overwrite the default toString() method by implementing it in your MonthDate class.

To format the int values you can use the String.format() method. The format %02d pads the value with a 0 if smaller than 10. To get the dd/mm format you can use %02d/%02d.

With that said your toString() method can look like this:

@Override
public String toString() {
    return String.format("%02d/%02d", this.day, this.month);
}

Using new MonthDate(12, 3) this would print:

12/03

Instead of:

MonthDate@42af3438
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
  • Thanks in advance! I still quite confuse, can you explain in more detail? – 陈俊杰 Mar 16 '19 at 12:01
  • 1
    @陈俊杰 every class in java is a child of Object, which has the method toString(). That's why System.out.printf calls toString for any Object it recieves. But the default implementation of toString for a new Class just prints the class name and a hash for the object which isn't very helpful, so you have to override the default implementation to make it print what you want, just like Samuel Philipp did – Philipp Hemmelmayr Mar 16 '19 at 12:05
  • @陈俊杰 I edited my answer and added an explanation to the `String.format()` method, hope that helps. – Samuel Philipp Mar 16 '19 at 12:32
0

Assuming that your MonthDate class attributes are

private int day;
private int month;

You should always implement a toString() method for every class in java because you will be representing every object differently.

As for sorting your objects by date, you cannot use Arrays.sort() because you're not sorting numbers. You should implement your own sorting method.Here's one i recommend you:

public static void sort(MonthDate[] s) {
    int[] days = new int[s.length];
    int[] months = new int[s.length];

    for (int i = 0; i < s.length; i++) {
        days[i] = s[i].day;
        months[i] = s[i].month;
    }

    Arrays.sort(days);
    Arrays.sort(months);

    for (int i = 0; i < s.length; i++) {
        s[i].day = days[i];
        s[i].month = months[i];
    }
}

We put the days and months in 2 different arrays and sorted them using Arrays.sort(), then assigned them back to the object instance.

You can also implement this toString() method and then call it in your print() method, because you cannot print an object directly with System.out.println().

public String toString() {
    return "" + this.day + "/" + this.month;
}

In your print() function you should use the toString() method as so:

public static <T> void print(T[] a) {
    for (T t : a) {
        System.out.println(t.toString());
    }
    System.out.println();
}

Finally, you can keep your main like that and it would sort it and print it correcty.

public static void main(String[] args) {
    MonthDate[] mdates = new MonthDate[5];
    mdates[0] = new SortMonthDate(22, 7);
    mdates[1] = new SortMonthDate(25, 8);
    mdates[2] = new SortMonthDate(25, 6);
    mdates[3] = new SortMonthDate(28, 9);
    mdates[4] = new SortMonthDate(5, 9);
    print(mdates);
    sort(mdates);
    print(mdates);
}

Here's the full code:

MonthDate class

import java.util.Arrays;

public class MonthDate {

    private int day;
    private int month;

    public MonthDate(int day, int month) {
        this.day = day;
        this.month = month;
    }

    public static void sort(MonthDate[] s) {
        int[] days = new int[s.length];
        int[] months = new int[s.length];

        for (int i = 0; i < s.length; i++) {
            days[i] = s[i].day;
            months[i] = s[i].month;
        }

        Arrays.sort(days);
        Arrays.sort(months);

        for (int i = 0; i < s.length; i++) {
            s[i].day = days[i];
            s[i].month = months[i];
        }
    }

    public String toString() {
        return "" + this.day + "/" + this.month;
    }

    public static <T> void print(T[] a) {
        for (T t : a) {
            System.out.println(t.toString());
        }
        System.out.println();
    }

}

SortMonthDate class

public class SortMonthDate {

    public static void main(String[] args) {


            MonthDate[] mdates = new MonthDate[5];
            mdates[0] = new MonthDate(22, 7);
            mdates[1] = new MonthDate(25, 8);
            mdates[2] = new MonthDate(25, 6);
            mdates[3] = new MonthDate(28, 9);
            mdates[4] = new MonthDate(5, 9);
            MonthDate.print(mdates);
            MonthDate.sort(mdates);
            MonthDate.print(mdates);

    }

}

Note that instead of making your MonthDate methods static, you could make them not static and call them in main using, for example, mdates.print();.

zin
  • 112
  • 8
  • “In your print() function you should use the toString() method” —Actually, `System.out.println(t)` is sufficient. toString() will be invoked automatically. – VGR Mar 16 '19 at 12:29
  • Those numbers are underlying and the complier said cannot applied to int, int. What is the problem? mdates[0] = new SortMonthDate(22, 7); mdates[1] = new SortMonthDate(25, 8); mdates[2] = new SortMonthDate(25, 6); mdates[3] = new SortMonthDate(28, 9); mdates[4] = new SortMonthDate(5, 9); – 陈俊杰 Mar 16 '19 at 13:17
  • @陈俊杰 at what line is the error? Can you put it here as it is? – zin Mar 16 '19 at 13:45
  • in the main part, mdates[0] = new SortMonthDate(22, 7); mdates[1] = new SortMonthDate(25, 8); mdates[2] = new SortMonthDate(25, 6); mdates[3] = new SortMonthDate(28, 9); mdates[4] = new SortMonthDate(5, 9); – 陈俊杰 Mar 16 '19 at 13:59
  • I can't help you if you don't copy paste the error as it is. – zin Mar 16 '19 at 16:20
  • @陈俊杰 make sure the day and month attributes in your MonthDate class are of type int not double or anything. – zin Mar 16 '19 at 22:47
  • So in the class MonthDate, I should only write this: private int day; private int month; public String toString() { return "" + this.day + "/" + this.month; } – 陈俊杰 Mar 27 '19 at 10:49
  • @陈俊杰 I added the full code to my answer, let me know if it works for you. – zin Mar 27 '19 at 15:56
  • It does not work. There is a warning message: "The constructor MonthDate(int, int) is undefined". But int the MonDate class, it has already declare the filed. – 陈俊杰 Mar 28 '19 at 00:52