I have an issue with accessing variables initialized in a switch-statement, and then using them outside switch.
This is what my code should produce:
What is: X (+-* or /) X
Here’s my Java code:
import java.util.Random;
import java.util.Scanner;
public class Test2 {
public static void main(String[]args){
Random rand = new Random();
Scanner sc = new Scanner(System.in);
int svar, ans;
int tal1 = rand.nextInt(100) + 1;
int tal2 = rand.nextInt(100) + 1;
String characters = "+-*/";
int r = rand.nextInt(characters.length());
char randomChar = characters.charAt(r);
switch(randomChar){
case '+':
ans = tal1 + tal2;
break;
case '-':
ans = tal1 - tal2;
break;
case '*':
ans = tal1 * tal2;
break;
case '/':
ans = tal1 / tal2;
break;
}
System.out.println("What is: "+tal1+randomChar+tal2+"?");
svar = sc.nextInt();
if (svar == ans)
System.out.println("Correct!");
else
System.out.println("Wrong - Right answer: "+ans);
}
}
As you can see, “ans” has been declared and initialized. However, I want to utilize the ans variable in both the if statement (in order to compare the result) and the output.
Now I could expand each case and write both the if statements and the outputs, but the code would be too exessive as I’m trying to do a similar code, but smaller. Any tips how this work would work?
Here’s the compilation error I get:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The local variable ans may not have been initialized
The local variable ans may not have been initialized
at Test2.main(Test2.java:36)
Add a
defaultcase to catch any input that isn’t recognized. In your case, this could throw aRuntimeException, since something is wrong with your code if this case is reached.The error you are getting means that there is a code path that fails to initialize
ans. Do not take the easy way out and initializeanswith a meaningless value when it is declared! That will just hide this valuable warning about a real problem with your code.