简体   繁体   中英

Java Calendar prints only zero

public class JavaCalender {
    int hour, minute, second;

    public void setCurrent() {
        Calendar calendar = new GregorianCalendar();
        this.hour = calendar.get(Calendar.HOUR_OF_DAY);
        this.minute = calendar.get(Calendar.MINUTE);
        this.second = calendar.get(Calendar.SECOND);
    }

    public int getHour() {
        return hour;
    }

    public int getMinute() {
        return minute;
    }

    public int getSecond() {
        return minute;
    }
}

class TestJavaCalender {
    public static void main(String[] args) {
        JavaCalender test = new JavaCalender();
        System.out.print(test.getHour() + "\n" + test.getMinute() + "\n" + test.getSecond());
    }
}

When I try to run this segment of codes, I could very disappointed, because the result does not equal my expectation. Why the result is all 0, could someone give me an incisive answer and how to use Calendar correctly?

Call the setCurrent() . Its unused for now.

JavaCalender test = new JavaCalender();
test.setCurrent();
System.out.print...

before you print. That's where the values would be set from as per your code.

Edit : Bringing up as mentioned in the comments by @Vikas

Adding to the part Why the result is all 0 . Because the default value for primitive int s in Java is 0 and as this answer points test.setCurrent() is never called, so that default value never gets updated.

From your test flow in TestJavaCalender class, you can change your "setCurrent()" method into constructor of JavaCalender class.
orignial:

public void setCurrent() {
    Calendar calendar = new GregorianCalendar();
    this.hour = calendar.get(Calendar.HOUR_OF_DAY);
    this.minute = calendar.get(Calendar.MINUTE);
    this.second = calendar.get(Calendar.SECOND);
}

after:

public JavaCalender() {
    Calendar calendar = new GregorianCalendar();
    this.hour = calendar.get(Calendar.HOUR_OF_DAY);
    this.minute = calendar.get(Calendar.MINUTE);
    this.second = calendar.get(Calendar.SECOND);
}

Then, you can use JavaCalender smoothly.

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