2017-06-07 27 views
0

您好我是新來的Java和我需要一點點主動幫助的問題是從編碼蝙蝠:CodingBat邏輯-1> caughtSpeeding

您駕駛的是有點太快了,和警察阻止你。編寫代碼來計算結果,編碼爲一個int值:0 =無票,1 =小票,2 =大票。如果速度爲60或更低,則結果爲0.如果速度在61和80之間,結果爲1.如果速度爲81或更高,結果爲2.除非是您的生日 - 在當天,您的在所有情況下速度可以高5。

public int caughtSpeeding(int speed, boolean isBirthday) { 
     Integer int2 = 0; 
     if (speed <= 60){ 
     int2 = 0; 
     } 
     if (isBirthday = true){ 
     if (speed >=61 && speed <= 85){ 
     int2 = 1; 
     } 
     if (speed >= 86){ 
     int2 = 2; 
     } 
     } 
     if (isBirthday = false){ 
     if (speed >=61 && speed <=80){ 
      int2 = 1; 
     } 
     if (speed >= 81){ 
      int2 = 2; 
     } 
     } 
     return int2; 
    } 

我越來越caughtSpeeding(65,真正的)應該是0的時候我的代碼運行到= 1和caughtSpeeding(85,假的)應爲2時,我的代碼運行爲= 1一次。

由於

+0

'='分配,''==平等 – Guy

+0

你說你是一個初學者,所以在注意:沒有理由爲'int2'使用'Integer'類型而不是'int'。如果你可以選擇,在你自己保存自動裝箱時使用原始類型。看[int vs整數](https://stackoverflow.com/questions/8660691/what-is-the-difference-between-integer-and-int-in-java/8660812#8660812) – Rhayene

回答

0

對於初學者來說,這一行:

if (isBirthday = true){ 

應改爲:

if (isBirthday == true){ 

,檢查是否兩個表達式等於等於運算符是==而不是= 。解決這個問題之後,還有其他的東西需要檢查你的代碼。再次仔細閱讀問題,並確保您的邏輯在所有可能的情況下返回正確的輸出。

0

稍微改變你的isBirthday if語句。

= // 'make this left-side value equal something'. 
== // 'comparison of two values' 

所以isBirthday你可以有

if(isBirthday) // is 'isBirthday' true? 
if(isBirthday == true) // same as above 

if(!isBirthday) // is 'isBirthday' not true (false)? 
if(isBirthday == false) // same as above 
0

固定它:

public int caughtSpeeding(int speed, boolean isBirthday) { 
     Integer int2 = 0; 
     if (speed <= 60){ 
     int2 = 0; 
     } 
     if (isBirthday == true){ 
     if (speed <=65){ 
     int2 = 0; 
     } 
     if (speed >=66 && speed <= 85){ 
     int2 = 1; 
     } 
     if (speed >= 86){ 
     int2 = 2; 
     } 
     } 
     if (isBirthday == false){ 
     if (speed >=61 && speed <=80){ 
      int2 = 1; 
     } 
     if (speed >= 81){ 
      int2 = 2; 
     } 
     } 
     return int2; 
    }