您将如何使用与参数的类名相同的名称添加时间偏移
Posted
技术标签:
【中文标题】您将如何使用与参数的类名相同的名称添加时间偏移【英文标题】:How would you add a time offset using the same name as the class name for the parameter 【发布时间】:2022-01-15 05:49:23 【问题描述】:我需要填写时间偏移的方法但是使用类名作为参数名我不知道怎么做 我尝试将变量添加在一起,但出现错误提示“您无法将 Time 转换为 int”
所以我不知道该怎么做, 请尽快回复 谢谢!
错误类型:
Time.java:48: error: bad operand types for binary operator '+'
this.minutes += offset;
^
first type: int
second type: Time
1 error
public class Time
// The values of the three parts of the time
private int hours;
private int minutes;
private int seconds;
public Time()
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
public Time(int h, int m, int s)
this.hours = h;
this.minutes = m;
this.seconds = s;
public void add(Time offset)
// Part b: complete the add method
public String toString()
return pad(hours) + ":" + pad(minutes) + ":" + pad(seconds);
private String pad(int value)
String sign = "";
if (value < 0)
sign = "-";
value = -1 * value;
if (value < 10)
return sign + "0" + value;
else
return sign + value;
public static void main(String[] args)
Time time1 = new Time(1,1,1);
Time time2 = new Time(2,2,2);
time1.add(time2);
System.out.println("The result of (1,1,1).add(2,2,2) is " +
time1 + " and should be (03:03:03)");
time1 = new Time(0,0,59);
time2 = new Time(0,0,1);
time1.add(time2);
System.out.println("The result of (0,0,59).add(0,0,1) is " +
time1 + " and should be (00:01:00)");
time1 = new Time(0,59,0);
time2 = new Time(0,0,1);
time1.add(time2);
System.out.println("The result of (0,59,0).add(0,0,1) is " +
time1 + " and should be (00:59:01)");
time1 = new Time(0,59,59);
time2 = new Time(0,0,1);
time1.add(time2);
System.out.println("The result of (0,59,59).add(0,0,1) is " +
time1 + " and should be (01:00:00)");
time1 = new Time(23,0,0);
time2 = new Time(1,0,0);
time1.add(time2);
System.out.println("The result of (23,0,0).add(1,0,0) is " +
time1 + " and should be (00:00:00)");
time1 = new Time(23,59,59);
time2 = new Time(23,59,59);
time1.add(time2);
System.out.println("The result of (23,59,59).add(23,59,59) is " +
time1 + " and should be (23:59:58)");
【问题讨论】:
我没听明白,抱歉。错误消息中引用的行不在您发布的代码中。然后很难提供帮助。请发布显示错误消息的代码。 【参考方案1】:你要把相应的时间部分加起来:
public void add(Time offset)
this.seconds = this.seconds + offset.seconds;
if(this.seconds >= 60)
this.seconds -= 60;
this.minutes += 1;
this.minutes += offset.minutes;
if(this.minutes >= 60)
this.minutes -= 60;
this.hours += 1;
this.hours += offset.hours;
if(this.hours >= 24)
this.hours -= 24;
【讨论】:
您可能不应该从小时数中减去 24。在现实生活中,时间可能比一天还长。 我同意,我一开始并没有这样做,但如果你看看他的第 5 次“测试”,他的预期输出为 (23,0,0) + (1,0,0)是 (00:00:00) 所以我添加了那行 @abra 非常感谢您的帮助以上是关于您将如何使用与参数的类名相同的名称添加时间偏移的主要内容,如果未能解决你的问题,请参考以下文章
为啥构造函数总是与类具有相同的名称以及它们是如何被隐式调用的?