0

I'm doing a calculator, in which is asked to the user to put two numbers, and then an aritmethical operator, so a set of IFs will understand what operator it is and do the operation required:

public class Calc {
   public static void main(String args[]) {
Scanner input = new Scanner(System.in);


System.out.print("First number: ");
double num1 = input.nextDouble();

System.out.print("Second number: ");
double num2 = input.nextDouble();

System.out.print("Artithemtical operator(-, +, :, x): ");
String segn = input.nextLine();


if(segn == "+" ) {
System.out.println(num1 + " + " + num2 + " = " + (num1 + num2));
}
else if(segn == "-") {
System.out.println(num1 + " - " + num2 + " = " + (num1 - num2));
}
else if(segn == "x") {
System.out.println(num1 + " x " + num2 + " = " + (num1 * num2));
}
else if(segn == ":") {
   System.out.println(num1 + " : " + num2 + " = " + (num1 / num2));
}


   }
}

as you can see if the input is a specific operator it will perform the specific task. It works well, it makes you put the two numbers, the operator but then it does nothing, what shall I do?

  • `==` checks for reference identity between objects, which is not what you want here. `segn.equals("x")` is right, `segn == "x"` won't get it done. – rzwitserloot Oct 11 '20 at 16:37

1 Answers1

0

String comparison should be perfomed with equals() method.

== compares your objects links in a heap to each other. And in your case they will be different. Because you have two completely different strings (in terms of java memory model) in each if statement.

One of that is the string that you're reading from input, and another one is the string which you're created inline, for example your "+" sign.

It is two different objects in memory, and when you're trying to compare links to them - they will be different.

Correct version of your class:

public class Calc {

  public static void main(String args[]) {
    Scanner input = new Scanner(System.in);

    System.out.print("First number: ");
    double num1 = input.nextDouble();
    input.nextLine(); //bug fix
    System.out.print("Second number: ");
    double num2 = input.nextDouble();
    input.nextLine(); //bug fix
    System.out.print("Artithemtical operator(-, +, :, x): ");
    String segn = input.nextLine();

    if (segn.equals("+")) {
      System.out.println(num1 + " + " + num2 + " = " + (num1 + num2));
    } else if (segn.equals("-")) {
      System.out.println(num1 + " - " + num2 + " = " + (num1 - num2));
    } else if (segn.equals("x")) {
      System.out.println(num1 + " x " + num2 + " = " + (num1 * num2));
    } else if (segn.equals(":")) {
      System.out.println(num1 + " : " + num2 + " = " + (num1 / num2));
    }
  }
}

And you have a small bug inside your class. It's related to using of Scanner. And your sign input is just ignored. Please, take a look into this.

evg_ny
  • 379
  • 2
  • 8