Java – Checking flags “if(flag=true)” is aways true in Java

booleanflagsjava

I'm trying to write a simple calculator program on Java. My first calculator program didn't have any problems registering the boolean flags signifying the operator as true or false (it dealt only with addition and subtraction) but when I implemented multiplication and division into the boolean, everything gets registered as true so that all the results for every operation is listed.

package com.arrdude.jason;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.lang.Math;

public class RegularCalculator {

public static void main(String[] args) {

    int var1 = 0;
    int var2 = 0;
    int operator = 0;
    boolean isAdd=false, isSub=false, isMult=false, isDiv=false;


try{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    System.out.println ("Enter the first number");
    var1=Integer.parseInt(br.readLine());

    System.out.println ("Enter the second number");
    var2=Integer.parseInt(br.readLine());

    System.out.println ("Which function do you wish you use? Enter 1 for addition, 2 for subtraction, 3 for multiplication, 4 for division");
    operator=Integer.parseInt(br.readLine());

}
catch(NumberFormatException ne) {
    System.out.println("Invalid number" + ne);
    System.exit(0);
}
catch(IOException ioe) {
    System.out.println ("IO Error" + ioe);
    System.exit(0);
}

if (operator==1){
    isAdd=true;
}
else{
    isAdd=false;
}
if (operator==2){
    isSub=true;
}
else{
    isSub=false;
}
/*if (operator==3){
    isMult=true;
}
else {
    isMult=false;
}
if (operator==4){
    isDiv=true;
}
else {
    isDiv=false;
}
*/
if(isAdd=true) {
    int result = var1 + var2;
    System.out.println("The result is " + result);
}
if(isSub=true) {
    int result = var1 - var2;
    System.out.println("The result is " + result);
}
if(isMult=true) {
    int result = var1 * var2;
    System.out.println ("The result is " + result);
}
if(isDiv=true) {
    int result = var1 / var2;
    System.out.println("The result is " + result);
}
}

}

If anyone can understand why this is happening, it'd be great. I'm pretty new to Java so I may have overlooked something that doesn't necessarily look out of place to a green eye. If you run the program, you should understand what kind of issue I'm running into.

Best Solution

If your last block of if statements, you have if(isAdd=true) and so on. This needs to be if(isAdd==true) (or even better, just if(isAdd)).

In fact, you could streamline things by just getting rid of all of the if statements and doing a switch statement based on the operator variable.