什么是数据字段?

时间:2016-12-03 09:30:52

标签: java

我应该修改Time2类(下面)以将时间实现为自午夜以来的秒数。该类应该有一个数据字段(一个int,其中包含自午夜以来的秒数),而不是三个。此更改不应影响公共方法的参数,行为或输出。

然后创建一个带有main方法的Driver类来测试你的Time2类。该程序应该要求用户输入午夜过后的小时数,分钟数和秒数,创建Time2对象并使用mutator方法。然后程序应该使用toString()方法打印出时间。

我的问题是以下代码的哪一部分是数据字段?

import java.util.Scanner;

public class Driver {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    Time2 time = new Time2();

    System.out.print("Enter hours:");
    int hours = input.nextInt();                                
    System.out.print("Enter minutes:"); 
    int minutes = input.nextInt();                              
    System.out.print("Enter seconds:"); 
    int seconds = input.nextInt();

    time.setSecond(seconds);    
    System.out.println(time.toString());
}

public static class  Time2 {

private  int  hour; 
private  int  minute;
private  int  second;   

public Time2() {this(0, 0, 0);}
public Time2(int  hour) {this(hour, 0, 0);}
public Time2(int  hour, int  minute) {this(hour, minute, 0);}

public Time2(int  hour, int  minute, int  second) {
    if(hour<0||hour>=24)
        throw new IllegalArgumentException("hour must be 0-23");
    if (minute < 0 || minute >= 60)
        throw new IllegalArgumentException("minute must be 0-59");
    if (second < 0 || second >= 60)
        throw new IllegalArgumentException("second must be 0-59");
    this.hour = hour;
    this.minute = minute;
    this.second = second;
}

public Time2(Time2 time) {this(time.getHour(), time.getMinute(), time.getSecond());}

public void setTime(int  hour, int  minute, int  second) {
    if (hour<0||hour>=24)
        throw new IllegalArgumentException("hour must be 0-23");
    if (minute < 0 || minute >= 60)
        throw new IllegalArgumentException("minute must be 0-59");
    if (second < 0 || second >= 60)
        throw new IllegalArgumentException("second must be 0-59");
    this.hour = hour;
    this.minute = minute;
    this.second = second;
}

public void setSecond(int  second) {
    if (second <= 0 || second > 60)
        throw new IllegalArgumentException("second must be 0-59");
    this.second = second;
}

public int  getHour() {return second/60/60;}
public int  getMinute() {return second/60;}
public int  getSecond() {return second;}

public String  toUniversalString() {
    return String.format( "%02d:%02d:%02d", getHour(), getMinute(), getSecond());
}

public String  toString() {
    return String.format("%d:%02d:%02d %s",
                          ((getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12), getMinute(),
                          getSecond(), (getHour() < 12 ? "AM" : "PM"));
}
}
}

~UPDATE~我得到的代码工作,唯一的问题是它显示错误的小时和分钟(见输出链接) output

1 个答案:

答案 0 :(得分:3)

A&#34;日期字段&#34;或&#34;数据成员&#34;是一个变量,它是类的一部分,并保存一些数据。在这种情况下,您有三个数据字段 - hourminutesecond(所有int s)。您的任务是使用单个字段second替换此实现,并调整方法&#39;相应的实施,以便他们保持行为。