在java中只使用一个实例变量打印2次

时间:2017-11-05 19:45:24

标签: java

这是它打印给我的东西
第一个Time2对象的小时是:18
第一个Time2对象的分钟是:33
第二个Time2对象的小时是:0
第二个Time2对象的分钟是:55

有人可以向我解释为什么第二个小时是0? 几乎忘记提到我只能使用一个实例变量

public class Time2
{
private int _minFromMid;
private final int _defaultVal = 0;

public static void main(String[] args) {
    Time2 firstTime = new Time2(18, 33);
    Time2 secondTime = new Time2(firstTime);

    System.out.println("The hour of the first Time2 object is: " + 
     firstTime.getHour());
    System.out.println("The minute of the first Time2 object is: " + 
    firstTime.getMinute());


    secondTime.setHour(16);
    secondTime.setMinute(55);

    System.out.println("The hour of the second Time2 object is: " + 
    secondTime.getHour());
    System.out.println("The minute of the second Time2 object is: " + 
    secondTime.getMinute());
  }

public Time2( int h , int m)
{     

    if(h > 23 || h < 0)
        h = _defaultVal;
    if(m > 59 || m < 0)
        m = _defaultVal;

    _minFromMid = (h * 60) + m;

}

public Time2(Time2 other)
{
    if(other != null)
        _minFromMid = other._minFromMid;

}

public int getHour()
{

    return _minFromMid / 60;

}

public int getMinute()
{

    return _minFromMid % 60;

}

public void setHour(int num)
{   

    if(num > 59 || num < 0)
        num = _defaultVal;

    _minFromMid = num;

}

public void setMinute(int num)
{

    if(num > 59 || num < 0)
        num = _defaultVal;

    _minFromMid = num;

}



public String toString()
{

    return Integer.toString(_minFromMid / 60) + ":" + 
    Integer.toString(_minFromMid % 60);

}

}

1 个答案:

答案 0 :(得分:0)

你的函数setHour和setMinute是错误的,它应该是:

public void setHour(int num)
{       
    if(num > 23 || num < 0)
        num = _defaultVal;

    _minFromMid = (num*60)+_minFromMid % 60;
}

public void setMinute(int num)
{

    if(num > 59 || num < 0)
        num = _defaultVal;

    _minFromMid = num + (_minFromMid/60)*60;

}

但是,我建议您使用两个变量,一个用于存储小时,另一个用于存储分钟。之后,您将需要实现getMinutesFromMid等函数。