-4

import java.util.*; // This is a package in through which take input in our calculator or any programme. public class SCalculator { public static void main(String[] args){

    System.out.println("Lets Calculate");
    System.out.println("Please enter the values:");
    Scanner sc = new Scanner(System.in);
    double a = sc.nextDouble();
    String operator = sc.next();
    double b = sc.nextDouble();

    if(operator == "+"){
        System.out.println("Equals to " + (a + b));
    }
    else if (operator ==  "-"){
        System.out.println("Equals to " + (a - b));
    }
    else if (operator == "*"){
        System.out.println("Equals to " + (a * b));
    }
    else if (operator == "/"){
        if(b == 0){
            System.out.println("Error");
        }
        else{
            System.out.println("Equals to " + (a / b));
        }
    }

when I input any value I donot get any out why kindly explain it;

what is difference between == operator and .equals()??

  • Never compare Strings with `==` or `!=` since these check to see if two String variables refer to the same object reference, and this is not what you're interested in. Instead use the `equals(...)` or `equalsIgnoreCase(...)` method to see if the two Strings have the same chars in the same order as that's what really matters here. – Hovercraft Full Of Eels Sep 02 '23 at 18:26
  • You can leave your code *largely* unchanged by doing `char operator = sc.next().charAt(0);` though of course single quotes will be necessary – g00se Sep 02 '23 at 18:26
  • Poor title. Rewrite to summarize your specific technical issue. – Basil Bourque Sep 02 '23 at 20:57
  • By the way… `switch` statement. `switch ( operator ) { case "+" -> System.out.println ( "Equals to " + ( a + b ) ); case "-" -> System.out.println ( "Equals to " + ( a - b ) ); case "*" -> System.out.println ( "Equals to " + ( a * b ) ); case "/" -> { if ( b == 0 ) { System.out.println ( "Error" ); } else { System.out.println ( "Equals to " + ( a / b ) ); } } }` – Basil Bourque Sep 02 '23 at 20:59

0 Answers0