2011-11-15 32 views
0

這裏的鏈接到我在做什麼,簡單的做法:
http://codingbat.com/prob/p162477不確定什麼是我做錯了,簡單的中間串

但是,它告訴我,當它使前面=假,

 public String theEnd(String str, boolean front) { 
      String stringPart; 
      if (front = true) { 
       stringPart = str.substring(0, 1); 
      } else { 
       stringPart = str.substring(str.length()-1,str.length()); 
      } 

      return stringPart; 
     } 

無論如何都會返回它的狀態。我不想學壞習慣:(

EX:大象返回E,當它應該返回牛逼後,我會回來檢查,我需要一個LOONNNNG休息大概做愚蠢的錯誤

回答

6

這是。問題:

if (front = true) 

您的意思是:

if (front == true) 

目前它分配front的012新值,然後評估該結果並發現它是真的 - 所以它會始終採取第一個字符。

有三種方法可以解決這個問題。其中一個如上,只是更加小心。一種是使用:

if (true == front) 

,這將防止您的錯字,因爲你不能分配給不斷true

不過,我更願意完全刪除字面的:

if (front) 

但是,您可以讓這整個方法具有簡單,條件運算符:

public String theEnd(String str, boolean front) { 
    int start = front ? 0 : str.length() - 1; 
    return str.substring(start, start + 1); 
} 
+0

Graah !!!我現在覺得自己像一個白癡:( 我已經瞭解了一千次的差異,並總是犯這個錯誤至少一次:D – JavaNewbie

0

你需要檢查是否與

if (front == true) 
0

你在if語句中寫了(front = true)。這並不比較正面和真實。這使前鋒等於真。

我很震驚你的編譯器沒有在你的這個聲明上大叫。你應該得到警告。如果可以,請確保您編譯時打開了所有警告選項,然後注意每個警告。