简体   繁体   English

Java时间显示意外结果?

[英]Java time displaying unexpected results?

The following is code which takes the three numbers (hours, minutes, and seconds) given in myobject.settime, and display them formatted correctly in military time. 以下是采用myobject.settime中给出的三个数字(小时,分钟和秒)的代码,并以军事时间正确显示它们的格式。 The problem is, when I am giving three numbers, the output on my console has three entirely different numbers. 问题是,当我给出三个数字时,控制台上的输出具有三个完全不同的数字。

public class Clock{
    public static void main (String [] args){
        Time myobject = new Time();
        System.out.println(myobject.tomilitary());
        myobject.settime(13, 27, 6 );
        System.out.println(myobject.tomilitary());
    }
}

class Time{
    private int hour, minute, second;

    public void settime(int h, int m, int s){
        hour = ((h>=0 && h<24) ? h : 0); //ternary operator, kind of like an if statement
        hour = ((m>=0 && m<60) ? m : 0);
        hour = ((s>=0 && s<60) ? s : 0);
        System.out.println(h +"\t" +m +"\t" +s +" \t The next line should display these three numbers");
    }

    public String tomilitary() {    
        return String.format("%02d:%02d:%02d", hour , minute , second ); //%02d means display two decimal places for each int after the quote.
    }                                                  
}

Right now my output is: 现在我的输出是:

 00:00:00
 13 27  6    The next line should display these three numbers
 06:00:00

But the last line of my output (06:00:00) should be (13:27:06) please explain what is going on. 但是我输出的最后一行(06:00:00)应该是(13:27:06),请解释发生了什么。

I guess your problem is this: 我猜你的问题是这样的:

hour = ((h>=0 && h<24) ? h : 0); //ternary operator, kind of like an if statement
minute= ((m>=0 && m<60) ? m : 0);
second = ((s>=0 && s<60) ? s : 0);

you assign three times hour hour分配3次

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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