与计算器的麻烦

时间:2015-04-26 19:50:52

标签: java calculator

我正在研究一个非常简单的Java计算器,它在选择操作后似乎没有输出答案。代码如下:

import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
    Scanner keyboard = new Scanner (System.in);
    Double fnum;
    Double snum; 
    Double answer;
    String operation; 
    System.out.println("Enter a number.");
    fnum = keyboard.nextDouble();
    System.out.println("Enter another number.");
    snum = keyboard.nextDouble();
    System.out.println("What operation do you wish for? [Multiplication, Addition, Subtraction, Division]");
    operation = keyboard.next(); 
    if (operation == "Multiplication" || operation == "multiplication" || operation == "*") { 
        answer = fnum * snum;
        System.out.print("Your answer is: " + answer);

    }   
    else if (operation == "Division" || operation == "division" || operation == "/") { 
        answer = fnum / snum;
        System.out.print("Your answer is: " + answer);

    }   
    else if (operation == "Addition" || operation == "addition" || operation == "+" || operation == "add") { 
        answer = fnum + snum;
        System.out.print("Your answer is: " + answer);

    }   
    else if (operation == "Subtraction" || operation == "subraction" || operation == "-" || operation == "subtract"){ 
        answer = fnum - snum;
        System.out.print("Your answer is: " + answer);

    }
      else {
        System.out.println("This is not valid.");
    }


}

}

这是输出:

Enter a number.
6
Enter another number.
6
What operation do you wish for? [Multiplication, Addition, Subtraction, Division]
Multiplication 
This is not valid.

非常感谢任何帮助。 附:没有错误。 谢谢!

4 个答案:

答案 0 :(得分:3)

有两个问题。扫描仪和条件

的问题

keyboard.nextDouble()keyboard.next()等...(除.nextLine()之外的所有内容)将换行符(\nEnter)留在缓冲区中。这可能会导致问题等。

我建议使用keyboard.useDelimiter("\n");添加分隔符。这只需要完成一次,可以在keyboard初始化后立即完成。

这样,它只会看到Enter作为结束当前输入的信号。

此外,条件必须全部使用.equals()方法或.equalsIgnoreCase()写成:

operation.equals("Multiplication");

operation.equalsIgnoreCase("multiplication");

答案 1 :(得分:0)

应通过.eqauals()方法比较字符串。所以放入if子句operation.equals(“乘法”)......依此类推......

答案 2 :(得分:0)

您是按引用比较字符串,而不是按值来比较。请改用.equals()

答案 3 :(得分:0)

正如@Sebastian所说,你应该使用equals而不是== 你可以通过以下方式改进它以避免空格错误或大小写(大写或小写)问题:

rData.csv

这样它可以用于乘法乘法,但也适用于MulTIpliCation等。

您也可以使用equalsIgnoreCase获得相同的结果