-1

I'm not getting any output out of this calculator. Can someone tell me why?

import java.util.*;  

public class JavaMain {

public static void main(String[] args) {
    float num1, num2;
    String op;
    float d, m, a, s;

    Scanner input = new Scanner(System.in);

    System.out.println("Calculator");

    System.out.print("Please enter an operation: ");
    op = input.next();


    System.out.print("First Number: ");
    num1 = input.nextFloat();

    System.out.print("Second Number: ");
    num2 = input.nextFloat();




        if (op == "+"){a = (num1 + num2);
            System.out.println(num1 + "+" + num2 + "=" + a);
        }


        if  (op == "-"){s = (num1 - num2 );
            System.out.println(num1 + "-" + num2 + "=" + s);
        }


        if (op == "/"){d = (num1/num2);
            System.out.println(num1 + "/" +num2 + "=" + d);
        }


        if (op == "*"){m = (num1*num2);
            System.out.println(num1 + "*" + num2 + "="+ m);
        }


    }

}// why am i not getting any outputs
riddle_me_this
  • 8,575
  • 10
  • 55
  • 80

2 Answers2

0

You are not comparing the string correctly. Use String.equals() method for string comparison. == checks if they are the same object not if they are equal logically. try the following code :

    if (op.equals("+")){
     a = (num1 + num2);
     System.out.println(num1 + "+" + num2 + "=" + a);
  }
thetraveller
  • 445
  • 3
  • 10
0

When dealing with strings we need to use string methods. That is we need to test equality with the equals() method. Furthermore your if statements should be if else if statements like so...

if (op.equals("+")) {
        a = (num1 + num2);
        System.out.println(num1 + "+" + num2 + "=" + a);
    }else if(op.equals("-")){
        s = (num1 - num2 );
        System.out.println(num1 + "-" + num2 + "=" + s);
    }else if(op.equals("/")){
        d = (num1/num2);
        System.out.println(num1 + "/" +num2 + "=" + d);
    }else{//if none of the above then the operation must be the remaining
        m = (num1*num2);
        System.out.println(num1 + "*" + num2 + "="+ m);
    }

You could have also used a switch case instead.