我怎样才能输入字符串数据?

时间:2018-05-12 08:46:02

标签: java calculator

import java.util.Scanner;

public class Basic {
    public static void main(String[] args) {
        Scanner CalcType = new Scanner(System.in);
        double fnum, snum;
        String math;

        System.out.println("--------------------------------------------------");
        System.out.println("Welcome to the basic calculator made by codermadi!");
        System.out.println("--------------------------------------------------");
        System.out.println("Enter first number!");
        System.out.println("--------------------------------------------------");

        fnum = CalcType.nextDouble();

        System.out.println("--------------------------------------------------");
        System.out.println("Enter second number!");
        System.out.println("--------------------------------------------------");

        snum = CalcType.nextDouble();

        System.out.println("--------------------------------------------------");
        System.out.println("+ | - | / | x | %");
        System.out.println("--------------------------------------------------");

        math = CalcType.next();

        if (math == "+") {
            System.out.println(fnum + snum);
        }
        if (math == "-") {
            System.out.println(fnum - snum);
        }
        if (math == "/") {
            System.out.println(fnum / snum);
        }
        if (math == "*") {
            System.out.println(fnum * snum);
        }
        if (math == "x") {
            System.out.println(fnum * snum);
        }
        if (math == "%") {
            System.out.println(fnum % snum);
        }

        System.out.println("-------------------------------------------");
        System.out.println("Thank you for using codermadi's calculator!");
        System.out.println("-------------------------------------------");
    }

}

我有一个问题,当我输入数学类型时,我希望我的计算器不会输出if语句。我的问题是粗体文字。

-

-

-

-

不得不添加这些因为StackOverFlow要我添加更多细节。

1 个答案:

答案 0 :(得分:0)

您不应该使用==来比较字符串对象。相反,请使用equals方法。有关它的更多信息https://stackoverflow.com/a/513839/8294285