Reputation: 595
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 == '-');
}
}
Upvotes: 1
Views: 271
Reputation: 21
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.
Upvotes: 2
Reputation: 24565
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.
Upvotes: 2
Reputation: 8387
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;
Upvotes: 2
Reputation: 234875
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.
Upvotes: 3
Reputation: 6077
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.
Upvotes: 3