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 == '-');
}
}






answill not be assigned. You may know that that is impossible, but the compiler does not know.