2013-07-19 61 views
0

(首先,我道歉,如果這是一個基本的問題,但我是新來的編碼)如何使用一個字符串和if-else語句?

什麼我想要做的是驗證使用字符串作爲字符的特定組合,然後是否替換它們if-else語句,如下所示:

String RAWUserInput = sometextfield.getText().toString(); 
if (RAWUserInput.contains("example") { 
    String UserInput = RAWUserInput.replace("example", "eg"); 
}else{ 
    String UserInput = RAWUserInput;} 

sometextbox.setText(UserInput); 

然後訪問if-else語句之外的字符串。我不知道如何去做最後一行,因爲java找不到字符串,我該怎麼辦?

感謝提前:)

+1

你確定它的牛嗎? : - }在'if-else'之外聲明你的字符串變量 – Smit

回答

4

if語句之前聲明變量。

String UserInput; 
if (RAWUserInput.contains("example") { 
    UserInput = RAWUserInput.replace("example", "eg"); 
}else{ 
    UserInput = RAWUserInput; 
} 

它將繼續在if聲明之後的範圍內。如果變量在if塊或else塊(位於花括號之間)內聲明,則在塊結束後超出範圍。

此外,編譯器足夠聰明,可以確定在每種情況下總是將某些內容分配給UserInput,因此您不會收到編譯器錯誤,指出該變量可能尚未分配值。

在Java中,與類不同,變量通常以小寫字母開頭。通常,您的變量將被命名爲userInputrawUserInput

4

當您在塊內聲明變量({ ... })時,該變量只存在於該塊內。

您需要在塊外聲明它,然後將它分配給塊內的

0
String rawUserInput = sometextfield.getText().toString(); 
String userInput = ""; // empty 
if (rawUserInput.contains("example") { 
    userInput = rawUserInput.replace("example", "eg"); 
} else{ 
    userInput = rawUserInput; 
} 

sometextbox.setText(userInput); 

否則,保存else語句:

String rawUserInput = sometextfield.getText().toString(); 
String userInput = new String(rawUserInput); // copy rawUserInput, using just = would copy its reference (e.g. creating an alias rawUserInput for the same object in memory) 
if (rawUserInput.contains("example") { 
    userInput = rawUserInput.replace("example", "eg"); 
} 
// no else here 

而且,看看編碼原則:縮進你的代碼使得它更具可讀性,開始以小寫臨時變量名是首選。

0
String UserInput = RAWUserInput.contains("example")? RAWUserInput.replace("example", "eg"): RAWUserInput;