简单的java计算器总是输出0

时间:2016-03-09 19:22:49

标签: java

我是java的新手,我正在尝试制作一个能够输入两个数字和一个运算符的小计算器。然后将该数据输入if语句以计算答案。然后输出到控制台。我遇到了问题,因为:

operator = Calc.next();

因为我认为上面的代码行对于输入字符串是正确的但是它不起作用,无论输入到计算器的数字是什么,答案似乎都输出为零。

请从pastebin链接中获取代码并查看它,因为我不确定出了什么问题。我很感激有人让我知道我哪里出错了。

http://pastebin.com/B5PjkXwX

由于

2 个答案:

答案 0 :(得分:1)

通过equals(String other)比较字符串,而不是通过==运算符。

if (operator.equals("+")) {
    answer = firstNumber + secondNumber;
} 
...

另外,我建议您将if-else语句转换为switch语句。

答案 1 :(得分:0)

import java.util.Arrays;
import java.util.Scanner;

public class Hello {

    public static void main(String args[]) {

        double firstNumber;
        double secondNumber;
        double answer = 0;
        String operator;

        Scanner Calc = new Scanner(System.in);

        System.out.println("\\\\CALCULATOR\\\\");

        System.out.println("Enter first number");
        firstNumber = Calc.nextDouble();

        System.out.println("Enter the math operator to use for this calculation");
        operator = Calc.next();

        System.out.println("Enter second number");
        secondNumber = Calc.nextDouble();

        if (operator.equals("+")) {
            answer = firstNumber + secondNumber;
        } else if (operator.equals("-")) {
            answer = firstNumber - secondNumber;
        } else if (operator.equals("/")) {
            answer = firstNumber / secondNumber;
        } else if (operator.equals("*")) {
            answer = firstNumber * secondNumber;
        }

        System.out.println(answer);
    }

}

或使用如下所示的开关

import java.util.Arrays;

import java.util.Arrays;
import java.util.Scanner;

public class Hello {

    public static void main(String args[]) {

        double firstNumber;
        double secondNumber;
        double answer = 0;
        String operator;

        Scanner Calc = new Scanner(System.in);

        System.out.println("\\\\CALCULATOR\\\\");

        System.out.println("Enter first number");
        firstNumber = Calc.nextDouble();

        System.out.println("Enter the math operator to use for this calculation");
        operator = Calc.next();

        System.out.println("Enter second number");
        secondNumber = Calc.nextDouble();

        switch (operator) {
        case "+":
            answer = firstNumber + secondNumber;
            break;
        case "-":
            answer = firstNumber - secondNumber;
            break;
        case "/":
            answer = firstNumber / secondNumber;
            break;
        case "*":
            answer = firstNumber * secondNumber;
            break;
        default:
            System.out.println("Incorrect operator");
            break;
        }

        System.out.println(answer);
    }

}