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

(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 :)

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.

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.

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.

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

Related

User inputs his first name inside a while loop how do I display the name later? [duplicate]

I'm a new programmer trying to practice by making a game.
I want the player to be able to set their own name, as well as answer yes or no as to whether that name is correct.
I did this by using a while loop.
However, since the name is initialized inside the loop, I cannot use it outside. I was wondering if there was anyway to do so.
My code is probably very basic and messy. I apologize for that.
Scanner input = new Scanner(System.in);
String name;
int nameRight = 0;
while (nameRight == 0) {
System.out.println("What is your name?");
name = input.nextLine();
System.out.println("So, your name is " + name + "?");
String yayNay = input.nextLine();
if (yayNay.equals("yes") || yayNay.equals("Yes")) {
System.out.println("Okay, " + name + "...");
nameRight++;
}
else if (yayNay.equals("no") || yayNay.equals("No")) {
System.out.println("Okay, then...");
}
else {
System.out.println("Invalid Response.");
}
}
So basically, I want String name to be initialized inside the loop, so I can use it outside the loop.
The scope of a variable, limits the use of that variable to the scope it is defined in. If you want it used in a broader scope, declare it outside the loop.
However, since the name is initialized inside the loop, I cannot use it outside.
You have defined the variable outside the loop, so the only thing you need to do is to initialize it, as the error message you should get suggests.
String name = "not set";
while(loop) {
name = ...
if (condition)
// do something to break the loop.
}
// can use name here.
The basic problem is that the compiler cannot work out that the variable will be set in all possible code paths. There is two ways you can fix this without using a dummy value. You can use a do/while loop.
String name;
boolean flag = true;
do {
name = ...
// some code
if (test(name))
flag = false;
// some code
} while(flag);
or drop the condition, as you don't need a counter.
String name;
for (;;) {
name = ...
// some code
if (test(name)) {
break;
// some code if test is false.
}
NO, it wouldn't be possible as the scope of the variable declared in the loop is limited to the loop. So the variable is not longer accessible.
while(i < 10){
int x = 2;
i++;
}
Now, the scope of x would be from the point at which it is defined to the end of the enclosing block. So the variable here would be created and destroyed 10 times if i starts from 0.
First there's the "scope", this is the issue you're touching at the moment. The way you have done this so far seems to be a good way of doing it and you WILL be able to use/access the name variable from anywhere in the code after line 2 from what you have linked.
The scope basically says, you can use the variable inside the curly brackets {} that you DECLARED it inside. I assume that you have your code inside some main method at the moment, thus you can access the name variable from anywhere after the line
String name;
as long as you don't try to use it after the closing }, corresponding to a opening { that occurred before name is declared.
SOLUTION: What you have to do to use a variable outside a loop, is to declare it before the loop begins, you don't have to initialize the variable before, but you have to initialize it before you try to use it for anything. In general, if you need to access the variable in a wider area, you must declare that variable before you enter the not-so-wide area.
Notice that by declaring I mean creating the variable reference by using "String" in front of "name". Don't confuse it with initializing it or assigning a value to it, that has nothing to do with the scope, only declaration sets the scope.

Variables in a do while loop

Below is some code asking the user to input an integer.
public int getValidInput() {
Scanner user_input = new Scanner(System.in);
do {
System.out.println("Enter an integer >=1 and <=10: ");
int number = user_input.nextInt();
} while (number > 10 || number < 0);
return number;
}
The code as shown does not work although when I initialise number outside the do command i.e. set it to int number; and then in the do loop set number = user_input.nextInt(); it does. Why does it work in one case and not the other?
Because in Java, variables are scoped to the block in which they're declared. In your example, the int number = is within the do...while block, and so the variable only exists within that block.
By moving the declaration out of the block, into the block for the method, the variable exists for the method's entire block (including nested blocks).
Your problem is that you have defined number inside your loop. Variables are scoped in Java, so variables declared inside loops or if statements are not accessible outside those loops or if statements. You can fix your code, simply by moving the declaration, as shown below:
public int getValidInput() {
Scanner user_input = new Scanner(System.in);
int number;
do {
System.out.println("Enter an integer >=1 and <=10: ");
number = user_input.nextInt();
} while (number>10 || number < 0);
return number;
}
The curly braces {} of the do-while open up a so called scope (they always do, wether in methods or loops or ifs). Any declaration inside a scope is only visible while you are within that scope, and also in any inner scope opened within the scope.
The condition of your while is outside the curly braces, so it does not see any variable declared within them. If you put the int number; before the do, it's on the same scope level like the while condition, so it, along with the value it gained inside the loop, is visible to the expressions in the condition.
Conditions are used to enter a body from outside that body, so the variable which decides the truth value of condition has to exist before the body.
And as the body block of do-while loop is the code to be executed, therefore the code which decides to execute it must be other than itself.
The scope of a variable restricted to {}. outside of that braces you cannot access. When you initialised it on top it access across both do and while as the scope is increased.

java Local variable not initializing outside if-statement

Eclipse says that the variable age, agirl and aboy may not have been initialized. I initialized the variables before the first if statement and they got values in the if-statement. When I want to use them in the next if-statement eclipse says the local variables may not have been initialized.
Here is my code:
import java.util.Scanner;
class Main{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String define;
int aboy, agirl, age;
System.out.println("Are you a boy or a girl?");
define = input.next();
if (define.equals("boy")){
System.out.println("What is your age?");
aboy = input.nextInt();
age = aboy;
}else if (define.equals ("girl")){
System.out.println("What is your age?");
agirl = input.nextInt();
age = agirl;
}else
System.out.println("wrong answer");
if (agirl >= 18 || aboy >= 16){
System.out.println("You are a " + define + " and you are " + age + " years old");
}
}
}
This line
int aboy, agirl, age;
contains declarations, not initializations. Java will not initialize a local variable for you, and there is an execution path (the else) where nothing is ever assigned to those variables, then you attempt to reference their nonexistent values.
You must set values to them before you use them, in all execution paths. Initialize them to something when you declare them.
Not only may you have an uninitialized variable, you're guaranteed to.
Look at your control flow: You first ask for a value for define, and then you execute exactly one of the blocks. If define is "boy", you don't initialize agirl; if define is "girl", you don't initialize aboy, and if define doesn't match either, you don't initialize any of your variables at all.
It looks like you are trying to cleverly combine the functions of a boolean and an int by having "magic" values in your ints. This is poor design because it's not clear how the magic works, but you can make your example run by initializing all of your int values to 0:
int aboy = 0, agirl = 0, age = 0;
Initializing is assigning the variable a value. Declaring is creating the variable. They are not the same.
The reason you need to initialize the variables is because it is possible they will not be initialized. All the if statements could be false, thus you need to give them a default value.

Reading and comparing strings in a text file, variables not initialized

I'm getting the error
the local variables name and password may not have been initialized,
for the if-statement. These errors go away if I change the second string in parentheses to something in quotes, or if I set the variables to 0, but then I would also need to change them to int and I need them to be String.
I'm trying to compare the username and password from a text file to a newly input username and password. The program should also quit after 3 bad attempts so I probably put the System.out.println("Goodbye!"); in the wrong place too.
public static void main(String[] args) {
int numberOfAttempts = 1;
String fileName = "logins.txt";
Scanner inputStream = null;
String name, password, line, secondname;
String secondpassword;
do
{
System.out.println("Please enter your username: ");
Scanner keyboard = new Scanner(System.in);
secondname = keyboard.nextLine();
System.out.println("Please enter your password: ");
secondpassword = keyboard.nextLine();
try
{
inputStream = new Scanner(new File(fileName));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " +
fileName);
System.exit(0);
}
while (inputStream.hasNextLine())
{
line = inputStream.nextLine();
}
if ((name.equalsIgnoreCase(secondname))&&
(password.equalsIgnoreCase(secondpassword)))
{System.out.println("Welcome!");
numberOfAttempts = 4;
}
else
System.out.println("Invalid. Please try again.");
numberOfAttempts++;
}
while ( numberOfAttempts <4);
System.out.println("Goodbye!");
inputStream.close();
}
}
You never initialize name and password, so of course you'll get this error.
You initialize secondname and secondpassword, but your condition checks name and password which are not initialized.
In JAVA methods, any local variable must be initialized first it can be used. In your case you are trying to compare the name & password in your code are never initialized or assigned a value.. It will be a good idea to initialize your strings either as NULL or empty string such as "" or any desired value.
You have a bunch of problems.
The errors are caused by the fact that you never assign any values to the variables "name" and "password", but you then check to see if those variables match the secondname and secondpassword variables you do read. Because name and password never get any values at all, the comparison can't possibly be what you intend, so the compiler flags it as an error.
You can make the error go away by assigning name and password to some values when you declare them, but your program still isn't going to work correctly, because no matter what value you assign, it probably won't be the thing that the user of your program would want to be comparing against.
Presumably your intent is to read the value of name and password from the input file you've opened and read in, but in fact you aren't doing anything with the values in that file except immediately throwing them away. Look at the loop
while(inputStream.hasNextLine()) {
line = inputStream.nextLine();
}
This loop will read in every line from the file, but as soon as you read one line, you throw away whatever you read into the line variable because you have to reuse that variable to read the next line, which you'll also throw away immediately. At the end of the loop, you'll have saved the last line from the file into line, but the rest of the program doesn't use the line variable either.
You need to put some logic inside that loop to read whatever you wanted to read from the file, store it in the name and password variables, and then you'll have some hope that when you do the equalsIgnoreCase stuff that you'll actually be comparing variables that have some meaning to your program.

What is wrong with my JAVA do loop?

I am learning JAVA and trying to write my first loop. The loop should prompt the user to guess a defined name.
The code is not performing right. I have tried to search for help on different JAVA tuturials both not found any examples where you guess a name/string but a lot where you should guess a number.
This is my code:
/**
*
* #author mso_
*/
import java.util.Scanner;
public class GuessName {
/**
* #param args the command line arguments
*/
public static final int C_Max_Trials = 10;
public static void main(String[] args) {
//Define correct name
String name = "Morten";
String guessName;
//Create a scanner
Scanner guess = new Scanner(System.in);
//Recieve a guess
do {
System.out.println("Please guess my name. Enter your guess here: ");
String guessName = guess.next(); <-- ERROR
//Create loop
} while (guessName != name); <-- ERROR
System.out.println("Sorry, wrong guess, please enter another guess: ");
if (guessName = name); <-- ERROR
System.out.println("Right on! ");
}
}
What have I done wrong?
String comparison
You can't compare Strings like this. This will only compare the references. You must use the equals() method :
while (! guessName.equals(name));
A little explanation : http://www.zparacha.com/java-string-comparison/
Variable redeclaration
There is another error in your code, you try to redeclare guessName inside the loop. You must declare guessName only once outside of the loop (ie before the do {).
General mistakes
Thirdly, there's a some other errors in your code. I think all of them were pointed out in the others answer, but I'll do a quick list :
if (guessName = name); This is a useless statement as is, you must open a block : if(condition) { statement; }
Same line, your doing an assignment, not a comparison, and like said, with String you must use .equals()
The System.out.println() won't be executed when you think. Re-read the doc about do { } while() loop until you really understand them.
My advise : read carefully the error message of your compiler and read some doc before writing code.
What errors?
Use .equals when comparing strings
You are using the assignment operator and not the equivalence operator at
if (guessName = name)
you need to do
if(guessName.equals(name)) instead.
You're comparing references (well, with guessName = name, you're actually assigning a value to guessName). Use String.equals() instead of == and !=.
you are comparing two objects. Not two string values.
use equals
That won't compile for a start - you declare String guessName on the third line of the main method, and then declare the same variable again within the do loop. You should simply use the name of the variable to assign to it:
guessName = guess.next();
Because of this error, presumably your IDE's compiler doesn't see the variable at all, so the subsequent lines that refer to guessName are also flagged as errors. Fixing this first line should clear those up, unless there's another problem lying there that I've missed.
Among other things there is a wrong semicolon after the if:
if (name.equals(guessName)) //removed the semicolon and use .equals
System.out.println("Right on! ");
and it's an assignment instead of a comparison as other answers state by now.
Try this
public class GuessName {
/**
* #param args the command line arguments
*/
public static final int C_Max_Trials = 10;
public static void main(String[] args) {
//Define correct name
String name = "Morten";
String guessName = null;
//Create a scanner
Scanner guess = new Scanner(System.in);
//Recieve a guess
do {
System.out.println("Please guess my name. Enter your guess here: ");
guessName = guess.nextLine(); <-- ERROR
if(!guessName.equals(name))
{
System.out.println("Sorry, wrong guess, please enter another guess: ");
}
//Create loop
} while (!guessName.equals(name)); <-- ERROR
if (guessName.equals(name)) <-- ERROR
System.out.println("Right on! ");
}
}
The line String guessName = guess.next(); needs to be changed to:
guessName = guess.next();
Because "guessName" is already defined earlier.
Additionally, when you compare strings you need to use the method equals and not the operator ==. So } while (guessName != name); should be:
} while (!guessName.equals(name));
And if (guessName = name); should be changed to:
if (guessName.equals(name))
Here is what the javac compiler says:
GuessName.java:26: guessName is already defined in main(java.lang.String[])
String guessName = guess.next(); //<-- ERROR
^
GuessName.java:32: incompatible types
found : java.lang.String
required: boolean
if (guessName = name);// <-- ERROR
^
2 errors
For the first one, you should not declare another local variable: drop the String. For the second, use .equals to compare String objects, as the doc says.
You will obtain something like that:
...
//Recieve a guess
do {
System.out.println("Please guess my name. Enter your guess here: ");
guessName = guess.next(); //<-- FIXED
//Create loop
} while (!guessName.equals(name)) //<-- FIXED
if (guessName.equals(name))// <-- FIXED
System.out.println("Right on! ");
}
...
which works correctly.
The strings must be compared using the equals method.

Categories