2013-05-22 16 views
1

我們被要求爲秒錶構建一個秒錶,其格式爲「##:##:###」並更新分鐘,秒和毫秒(私有實例變量)因此。例如,"1:21:300"表示1分21秒300毫秒。在Java中使用parseInt分割字符串

所以我想用string.split()配對parseInt更新值。但是,該程序不會編譯。我的構造函數根據eclipse具有正確的語法,但是我正在做的事情有問題。我從來沒有使用splitparseInt,所以我可能會使用這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"); 
+1

什麼是你的秒錶的ToString()?如果你沒有定義一個,你就繼承了Object中的一個,它不會做你想做的事。 –

+0

或者如果你有一個我認爲你可能有領先0的問題 – cerkiewny

回答

2

正如在其他的答案中提到,長度是關閉的各1各,但指數的if塊也關閉你正在使用的;例如。如果長度爲1時,唯一可用的指數是0,如果長度爲2,可用該指數的0和1

這樣你可以獲得一個構造函數,看起來像:

class StopWatch { 
    int minutes; 
    int seconds; 
    int milliseconds; 

    public StopWatch(String startTime) { 
     String[] timeArray = startTime.split(":"); 

     if (timeArray.length == 3) { 
      this.minutes = Integer.parseInt(timeArray[0]); 
      this.seconds = Integer.parseInt(timeArray[1]); 
      this.milliseconds = Integer.parseInt(timeArray[2]); 
     } else if (timeArray.length == 2) { 
      this.minutes = 0; 
      this.seconds = Integer.parseInt(timeArray[0]); 
      this.milliseconds = Integer.parseInt(timeArray[1]); 
     } else if (timeArray.length == 1) { 
      this.minutes = 0; 
      this.seconds = 0; 
      this.milliseconds = Integer.parseInt(timeArray[0]); 
     } else { 
      this.minutes = 0; 
      this.seconds = 0; 
      this.milliseconds = 0; 
     } 
    } 
} 
+0

非常感謝!快速和有益的答案。 – Enormosaurus

+0

@ user2407581 - 我們希望提供足夠的提示足以讓您走上正軌。 –

0
if(timeArray.length == 2){ 

應該是:

if(timeArray.length == 3){ 

等。

20:10:8分割的條件:給你的3的長度;)

1

雖然Java數組是基於零的,它們的長度簡單地計算元件的數量。因此,{1,2,3}.length將返回3

由於您的代碼現在寫入,您將會在左右出現ArrayOutOfBounds例外情況。

2

請以你的toString()方法:

public String toString() { 
    String paddedMinutes = String.format("%02d", this.minutes); 
    String paddedSeconds = String.format("%02d", this.seconds); 
    String paddedMilliseconds = String.format("%03d", this.milliseconds); 
    return paddedMinutes + ":" + paddedSeconds + ":" + paddedMilliseconds; 
} 
+0

我不知道%02d是什麼。這只是我第二個學期的程序設計(並且我在兩個學期之間轉到了另一所大學,這是一個很大的錯誤)。儘管如此,我會進一步研究,謝謝你的迴應。 – Enormosaurus

+0

這是一個很好的建議,但問題在給定的代碼中已經很明顯。 –

+0

@ user2407581'%.. d'將被給定數字(d)值的字符串表示替換。 2表示最多兩位數字,0表示處理器應將值填充爲零,直到達到最大大小(因此總是得到兩位數字)。 –