繁体   English   中英

如何在if-else语句中使用字符串?

[英]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中,与类不同,变量通常以小写字母开头。 通常,您的变量将命名为userInputrawUserInput

当您在块( { ... } )中声明变量时,该变量仅存在于该块内部。

您需要在块外部声明它,然后在块内部分配它。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM