[英]How can I use a string out of and if-else statement?
(首先,我很抱歉這是一個基本問題,但是我是編碼新手)
我想要做的是驗證字符串是否為某些字符的組合,然后使用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找不到字符串,我該怎么辦?
提前致謝 :)
在if
語句之前聲明變量。
String UserInput;
if (RAWUserInput.contains("example") {
UserInput = RAWUserInput.replace("example", "eg");
}else{
UserInput = RAWUserInput;
}
在if
語句之后,它將保留在范圍內。 如果在if
塊或else
塊內(在大括號之間)聲明了變量,則該變量將if
塊末尾超出范圍。
同樣,編譯器足夠聰明,可以確定在每種情況下總是將某些內容分配給UserInput
,因此不會出現編譯器錯誤,即可能未為變量分配值。
在Java中,與類不同,變量通常以小寫字母開頭。 通常,您的變量將命名為userInput
和rawUserInput
。
當您在塊( { ... }
)中聲明變量時,該變量僅存在於該塊內部。
您需要在塊外部聲明它,然后在塊內部分配它。
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
另外,請查看編碼准則:縮進代碼使其更具可讀性,首選以小寫字母開頭的臨時變量名。
String UserInput = RAWUserInput.contains("example")? RAWUserInput.replace("example", "eg"): RAWUserInput;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.