转换后如何打印出这个私有类字段?

时间:2014-01-22 02:28:35

标签: java class printing private

我已经在这个任务上工作了一段时间,而且我碰到了一堵我无法想象的墙。可以在这里阅读作业的目标,以免我输入或复制它的麻烦。

http://imgur.com/be5YVst

我无法弄清楚作业的输出部分。因为必须以这种特定方式设置类,而不仅仅是执行特定功能。即使赋值没有说明toString()或类似的方法,我开始写一个,但意识到我不能使用字段,小时,分钟和秒,因为它们超出了范围。如果我试图将它们放入TimeTest程序中,我将无法获得许可,因为它们是私有的。 (他们必须是私人的。)

如何以小时:分钟:秒?

的形式打印出这些转换后的单位

以下是我目前的代码:

public class Time 
{
    private long hour;
    private long minute;
    private long second;

    public Time()
        {
            long compTime = System.currentTimeMillis();
            this.setTime(compTime);
        }

    public Time(long hour, long minute, long second)
        {
            this.hour = hour;
            this.minute = minute;
            this.second = second;
        }

    public Time(long time)
        {
            this.setTime(time);
        }

    //three get methods
    public long getHour()
        {
            return this.hour;
        }

    public long getMinute()
        {
            return this.minute;
        }

    public long getSecond()
        {
            return this.second;
        }
    //setTime method
    public void setTime(long elapseTime)
        {
            this.hour = (elapseTime/36000000);
            this.minute = ((elapseTime - (this.hour * 36000000))/60000);
            this.second = ((elapseTime - (this.minute * 60000))/1000);
        }

    public String printFormat()
        {
        //it wouldn't let me name it toString() so I named it printFormat() instead.
        }
}

2 个答案:

答案 0 :(得分:0)

@Override
public String toString() {

    // create a string from your fields

}

答案 1 :(得分:0)

  

试试这个,

 class Time 
    {
        private long hour;
        private long minute;
        private long second;

        public Time()
        {
            long compTime = System.currentTimeMillis();
            this.setTime(compTime);
        }

        public Time(long hour, long minute, long second)
        {
            this.hour = hour;
            this.minute = minute;
            this.second = second;
        }

        public Time(long time)
        {
            this.setTime(time);
        }

        //three get methods
        public long getHour()
        {
            return this.hour;
        }

        public long getMinute()
        {
            return this.minute;
        }

        public long getSecond()
        {
            return this.second;
        }
        //setTime method
        public void setTime(long elapseTime)
        {
            this.hour = (elapseTime/36000000);
            this.minute = ((elapseTime - (this.hour * 36000000))/60000);
            this.second = ((elapseTime - (this.minute * 60000))/1000);
        }

        public String printFormat()
        {
            return hour + ":" + minute + ":" + second;
        }
    }
    public class TimeTest
    {
        public static void main(String[] args)
        {
            System.out.println(new Time().printFormat());
        }
    }