1

I'm writing a simple program with a do while loop and switch, which cna accept a mathematical operation and execute it for given 2 numbers.

The problem I have is, why should I initialize the result produced by the operation to zero at the beginning.

If I don't make ans=0, it gives me errors. If the given conditions are not met, some code parts are not executed and I don't need "ans".

package q3;
import java.util.Scanner;

public class Q3 {
public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    char operator;
    float no1, no2, ans=0; // <-------------- Why should I initialize ans

    do {
        System.out.println(" Mathematical Operations to be performed :");
        System.out.println("\t * Multiplication\n\t / Division\n\t + Addition\n\t - Subtraction");
        System.out.println("Press any other character to exit");
        System.out.print("Mathematical Operator : ");
        operator = input.next().charAt(0);

        if (operator == '*' || operator == '/' || operator == '+' || operator == '-') {
            System.out.print("Number 1: ");
            no1 = input.nextFloat();
            System.out.print("Number 2: ");
            no2 = input.nextFloat();

            switch (operator) {
                case '*':
                    ans = no1 * no2;
                    break;
                case '/':
                    ans = no1 / no2;
                    break;
                case '+':
                    ans = no1 + no2;
                    break;
                case '-':
                    ans = no1 - no2;
                    break;
            }

            System.out.println("The answer of " + no1 + operator + no2 + " = " + ans);

        }
    } while (operator == '*' || operator == '/' || operator == '+' || operator == '-');

}

}

2
  • 1
    Why? Please rephrase your question to make more sense.. Commented Feb 4, 2016 at 13:40
  • As far as Java's compiler can determine, it is possible that none of the cases in your switch statement will be matched, and ans will not be assigned. You may know that that is impossible, but the compiler does not know. Commented Feb 4, 2016 at 13:41

5 Answers 5

3

Java requires that all local variables are initialised before they are used.

In your print line, you read the value of abs, but not all control paths set a value to it. (Even though you think you've covered all possibilities of your switch given the outer if, the compiler will not see things that way: some other thread could modify operator).

So your IDE / compiler is suggesting that you initialise it at the point of declaration.

Sign up to request clarification or add additional context in comments.

5 Comments

so should I use the default case in switch here?
I would do that, and drop the if.
but if I drop if, the no1 and no2 values will have to be assigned and it'll be unnecessary since no operation is to be done.??!
Yup. You're stumbling upon a redesign. You should build a function that computes the arity of your operator. That replaces the if. Then you know how many arguments you need. Then you'll be able to distinguish negation from subtraction, and can handle expressions like 1 * -1'
Nothing yet, but expression parsers tend to get more complicated. It's all about designing for future requirements.
3

This is because if no case evaluates to true, the value of ans will not be set. So you cannot use it.

You can overcome this by adding a default case, and setting the value of ans as 0 in that.

2 Comments

if the given conditions haven't met this doesn't let the switch or any other code to execute, what's the point of initializing then?
@laish129 Yes, But the java compiler cannot understand all such things, because it is in if construct, which may, or may not evaluate !
2

You should initialize ans=0; because you didn't have a default value for ans, for this you need to initialized it.
But if you add the defualt value you don't need to initialize it like this:

    ...
    case '-':
    ans = no1 - no2;
      break;
    default :
    ans = someValue; 
     break; 

Comments

2

Well, it could be that none of the case statements apply and as a result ans would still be un-initialized. And since local variables have to be initialised before they are being used, you get this error.

Comments

2

If you didnt initialize it, you ans will have a garbage value at first.

It is not compulsory to initialize it.

But your program will be a better program if you initialize it.

2 Comments

This is true for C/C++, not for Java?
In C and C++, the behaviour on reading back an uninitialised value is undefined. In Java, such a construct must fail on compilation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.