【发布时间】:2013-05-22 00:50:17
【问题描述】:
我们被要求为 Stopwatch 构建一个构造函数,该构造函数接受格式为“##:##:###”的字符串并相应地更新分钟、秒和毫秒(私有实例变量)。例如,"1:21:300" 表示 1 分 21 秒 300 毫秒。
所以我尝试使用string.split() 与parseInt 配对来更新值。但是,该程序不会编译。根据 eclipse,我的构造函数具有正确的语法,但是我正在做的事情有问题。我从未真正使用过split 或parseInt,所以我可能100% 错误地使用了这些。谢谢。
public StopWatch(String startTime){
String [] timeArray = startTime.split(":");
if(timeArray.length == 2){
this.minutes = Integer.parseInt(timeArray[0]);
this.seconds = Integer.parseInt(timeArray[1]);
this.milliseconds = Integer.parseInt(timeArray[2]);
}
else if(timeArray.length == 1){
this.minutes = 0;
this.seconds = Integer.parseInt(timeArray[1]);
this.milliseconds = Integer.parseInt(timeArray[2]);
}
else if(timeArray.length == 0){
this.minutes = 0;
this.seconds = 0;
this.milliseconds = Integer.parseInt(timeArray[2]);
}
else{
this.minutes = 0;
this.seconds = 0;
this.milliseconds = 0;
}
}
附: Junit 测试在尝试执行操作时显示“ComparisonFailue:预期为 0:00:000 但为 20:10:008”:
s = new StopWatch("20:10:8");
assertEquals(s.toString(),"20:10:008");
【问题讨论】:
-
你的 StopWatch.toString() 是什么?如果你没有定义一个,你就是从 Object 继承一个,它不会做你想要的。
-
或者如果你有一个,我认为你可能对前导 0 有问题