Luso
Luso

Reputation: 135

How can I use a string out of and if-else statement?

(First of all, I apologize if this is a basic question, but I'm new to coding)

What i want to do is to verify whether a string as a certain combination of characters and then replace them using an if-else statement, like this:

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

sometextbox.setText(UserInput);

and then access the string outside of the if-else statement. I don't know how to do the last line because java can't find the string, What should I do?

Thanks in advance :)

Upvotes: 0

Views: 1267

Answers (4)

HunkD
HunkD

Reputation: 76

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

Upvotes: 0

pyb
pyb

Reputation: 5269

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

sometextbox.setText(userInput);

Otherwise, save the else statement:

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

Also, have a look at coding guidelines: indenting your code makes it more readable, starting temporary variable names with a lowercase is preferred.

Upvotes: 0

SLaks
SLaks

Reputation: 887275

When you declare a variable inside a block ({ ... }), the variable only exists inside that block.

You need to declare it outside the block, then assign it inside the blocks.

Upvotes: 4

rgettman
rgettman

Reputation: 178253

Declare the variable before the if statement.

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

It will remain in scope after the if statement. If the variable is declared inside the if block or else block (in between the braces), then it goes out of scope after the end of the block.

Also, the compiler is smart enough to determine that something is always assigned to UserInput in every case, so you won't get a compiler error that the variable may not have been assigned a value.

In Java, variables are typically named starting with a lowercase letter, unlike classes. Normally, your variables would be named userInput and rawUserInput.

Upvotes: 4

Related Questions