2

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)
danielk
  • 37
  • 2
  • 5

7 Answers7

3

Add a default case to catch any input that isn't recognized. In your case, this could throw a RuntimeException, since something is wrong with your code if this case is reached.

default: 
  throw new RuntimeException("Unexpected operation: " + randomChar);

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 initialize ans with a meaningless value when it is declared! That will just hide this valuable warning about a real problem with your code.

erickson
  • 265,237
  • 58
  • 395
  • 493
  • Much appreciated, thanks! So an initialized local variable like (int ans = 0;) should only be there if a default case is not practical? – danielk Nov 29 '11 at 20:05
  • If you unconditionally initialize a variable with a value, *that is the default case.* You should only do that if zero is a valid value for `ans` that your program can use in a meaningful way. – erickson Nov 29 '11 at 20:11
1

Unlike instance variables, local variables are not automatically initialized.

You need to explicitly initialize it the default value.

 int svar, ans = 0; // assuming 0 is default value for ans

If all the cases fail in your switch then ans will never be initialized.

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
0

Local variables such as ans must be initialized prior to usage.

So just assign zero to ans

Mechkov
  • 4,294
  • 1
  • 17
  • 25
0

If you declare a local var (inside a function) you should always initialize it

int svar = 0;
int ans = 0;

if you declare it outside of a function then it will be automatically initialized with 0, but that's not good practice for this one

vanleeuwenbram
  • 1,289
  • 11
  • 19
0

You get this compilation error because compiler doesnt know if ans will ever be initialized, reason being at the compile time it is not known if the switch condition will ever be executed hence the compilation error. To resolve it initialize ans to some value like :

ans = -1;

Also take a look at this post and this

Community
  • 1
  • 1
mprabhat
  • 20,107
  • 7
  • 46
  • 63
0

Just change your declaration int svar, ans; to int svar, ans=0; to remove this error. Problem is that your variable ans is not initialized at this line: if (svar == ans) and your switch case doesn't have default case.

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

You did not initialize ans before the switch.

I don't recommend erikson's answer, as your randomChar will only give you handled inputs (you'll never reach default case).

user1071777
  • 1,307
  • 1
  • 15
  • 23