'Why cant i use this input variable? [duplicate]
float x = 12.1f;
float y = 0.8f;
float z = 9.81f;
boolean key2 = false;
while (!key2) {
try {
Scanner scanner2 = new Scanner(System.in);
System.out.println("What is the velocity?: ");
float TheNumber = scanner2.nextFloat();
key2 = true;
}//end of try
catch(Exception e) {
System.out.println("Thats not a number, try again");
}// end of catch
}//end of while
float result = 2 + x + y + TheNumber + z; // Why cant i use "TheNumber" variable ?
output: TheNumber cannot be resolved to a variable
Hey guys, im having a problem trying to use a variable inside the while loop, i come from Python so its all a little new for me, is there a reason i cant use variables? and if so, how could i use it?
Solution 1:[1]
TheNumber is scoped to the try block.
This question is very similar to this one - Why does a Try/Catch block create new variable scope? .
Also see this tutorial - https://www.baeldung.com/java-variable-scope
Solution 2:[2]
You have to define the variable outside the loop. If you define it inside the loop, then it only exists inside the loop. So try this:
float x = 12.1f;
float y = 0.8f;
float z = 9.81f;
float TheNumber;
boolean key2 = false;
while (!key2) {
try {
Scanner scanner2 = new Scanner(System.in);
System.out.println("What is the velocity?: ");
TheNumber = scanner2.nextFloat();
key2 = true;
}//end of try
catch(Exception e) {
System.out.println("Thats not a number, try again");
}// end of catch
}//end of while
float result = 2 + x + y + TheNumber + z;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | John Aronson |
| Solution 2 | Jhanzaib Humayun |
