1

Does anyone know why when i run this java application, it keeps coming up with the default value, and not the correct answer?

The main code is below:

import java.util.Scanner;

public class mainClass {
public static void main(String[] args){

    Scanner scanInt = new Scanner(System.in);
    Scanner scanString = new Scanner(System.in);

    System.out.println("Calculator");
    System.out.println("Enter 1st number:");
    int x = scanInt.nextInt();

    System.out.println("Enter opperation:");
    String op = scanString.nextLine();
    System.out.println(op);

    System.out.println("Enter 2nd number:");
    int y = scanInt.nextInt();

    String ans = "The answer is: ";

    if(op == "+"){
        System.out.println(ans + methods.addition(x, y));
    }else if(op == "-"){
        System.out.println(ans + methods.subtraction(x, y));
    }else if(op == "*"){
        System.out.println(ans + methods.multiplication(x, y));
    }else if(op == "/"){
        System.out.println(ans + methods.division(x, y));
    }else{
        System.out.println("UNKNOWN OPPORATOR");
    }
}
}

The methods class is below:

public class methods {
public static int subtraction(int x, int y){
    return x - y;
}
public static int addition(int x, int y){
    return x + y;
}
public static int multiplication(int x, int y){
    return x * y;
}
public static int division(int x, int y){
    return x / y;
}
}
Crippledsmurf
  • 3,982
  • 1
  • 31
  • 50
Shuba
  • 376
  • 2
  • 6
  • 14

1 Answers1

8

You cannot compare string values with the == operator. The == operator compares two object references to determine if they refer to the same object.

To compare string values, use String#equals:

if("+".equals(op){

and likewise for the other comparisons.

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • 1
    More precisely, you CAN compare instances of java.lang.String with the `==` operator, but only if they have been interned. – rees Apr 25 '13 at 16:38
  • 1
    Even more precisely, you can *always* compare instances of java.lang.String with the `==` operator, but it may not do what you actually want it to do. :) – yshavit Apr 25 '13 at 16:44