1

有谁知道为什么当我运行这个 java 应用程序时,它不断出现默认值,而不是正确的答案?

主要代码如下:

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");
    }
}
}

方法类如下:

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;
}
}
4

1 回答 1

8

您不能将字符串值与==运算符进行比较。运算符比较==两个对象引用以确定它们是否引用同一个对象。

要比较字符串值,请使用String#equals

if("+".equals(op){

其他比较也是如此。

于 2013-04-25T16:36:48.570 回答