【发布时间】: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)");
}
}
【问题讨论】:
-
我没听明白,抱歉。错误消息中引用的行不在您发布的代码中。然后很难提供帮助。请发布显示错误消息的代码。