为什么我没有得到任何输出?

时间:2016-10-26 23:09:26

标签: java calculator polish

我没有从这个计算器中获得任何输出。有人可以告诉我为什么吗?

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

2 个答案:

答案 0 :(得分:0)

您没有正确比较字符串。使用String.equals()方法进行字符串比较。如果它们在逻辑上相等,则==检查它们是否是同一个对象。 尝试以下代码:

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

答案 1 :(得分:0)

处理字符串时,我们需要使用字符串方法。那就是我们需要用equals()方法测试相等性。此外,你的if语句应该if if else if so 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);
    }

你也可以使用开关盒。