我們被要求爲秒錶構建一個秒錶,其格式爲「##:##:###」並更新分鐘,秒和毫秒(私有實例變量)因此。例如,"1:21:300"
表示1分21秒300毫秒。在Java中使用parseInt分割字符串
所以我想用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;
}
}
P.S. JUnit測試說 「ComparisonFailue:預計0:00:000,但被20:10:008」 試圖做的時候:
s = new StopWatch("20:10:8");
assertEquals(s.toString(),"20:10:008");
什麼是你的秒錶的ToString()?如果你沒有定義一個,你就繼承了Object中的一個,它不會做你想做的事。 –
或者如果你有一個我認爲你可能有領先0的問題 – cerkiewny