Question

I am new to programming and would appreciate some help. The slightest bit of insight would be highly appreciated. I have an issue with the following code. The program emulates a calculator but currently my main focus is on if and else if statements. The issue is that no matter what the user selects, the program will always add the two numbers i.e. 'number1' and 'number2' in the code

import java.util.*;
public class Input
{
    private Scanner input;

    public Input()
    { 
        input = new Scanner(System.in);

    }

    public void calculation()
    {
        double number1, number2, answer;
        String A, B, C, D, E;
        String option;
        A = "A"; B = "B"; C = "C"; D = "D"; E = "E"; //initialising the strings 

        System.out.println("add - option A \t (if your option is A, insert 'A')");
        System.out.println("multiply - option B");
        System.out.println("subtract - option C");
        System.out.println("divide - option D");
        System.out.println("power - option E (1st number - 'X' & 2nd number - 'n' following X^n)");
        System.out.println("Remember Java is case sensitive, therefore, inserting 'a' as 'A' won't work");
        System.out.println();
        System.out.println("Insert your first number: ");
        number1 = input.nextDouble();
        System.out.println("Insert your second number: ");
        number2 = input.nextDouble();
        System.out.println("Choosing option: ");
        option = input.next();

        if(A == A)
        {
            answer = number1 + number2;
            System.out.println("Your answer is: " + answer);
        }

        else if(B == B)
        {
            answer = number1 * number2;
            System.out.println("Your answer is: " + answer);

        }else if(C == C)
        {
            answer = number1 - number2;
            System.out.println("Your answer is: " + answer);

        }else if(D == D)
        {
            answer = number1 / number2;
            System.out.println("Your answer is: " + answer);

        }else if(E == E)
        {
            answer = Math.pow(number1, number2);
            System.out.println("Your answer is: " + answer);

        }else
        {
            System.out.println("Choose a suitable option");

        }    
    }
}
Was it helpful?

Solution

Youre getting the selected option from user input in option = input.next(); line and than your not using it in your if statements.

Instead of if(A == A) use if(option.equals(A)) and so on for other cases.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top