为什么我的程序不能使用我指定的字符串运算符来计算两个整数?

时间:2012-09-22 15:48:10

标签: java

  

可能重复:
  How do I compare strings in Java?

为什么我的程序不能使用我指定的字符串运算符来计算两个整数?由于某些原因,它好像程序不接受用户的输入。

import java.io.*;

public class IntCalc {
    public static void main (String [] args) throws IOException {
        BufferedReader kb = new BufferedReader (new InputStreamReader (System.in));

        System.out.println ("This program performs an integer calculation of your choice.");

        System.out.println ("Enter an integer: ");
        int x = Integer.parseInt (kb.readLine());

        System.out.println ("Enter a second integer: ");
        int y = Integer.parseInt (kb.readLine());

        System.out.print ("Would you like to find the sum, difference, product, quotient, or remainder of your product?: ");
        String operator = kb.readLine();

        int finalNum;

        if (operator == "sum") {
            int finalNum = (x + y);
        } else if (operator == "difference") {
            int finalNum = (x - y);
        } else if (operator == "product") {
            int finalNum = (x * y);
        } else if (operator == "remainder") {
            int finalNum = (x % y);
        }

        System.out.print ("The " + operator + " of your two integers is " + finalNum ".");
    }
}

3 个答案:

答案 0 :(得分:4)

您需要在此处删除int声明中的if声明。此外,在比较字符串时使用String.equals()。确保初始化finalNum或编译器会抱怨。

int finalNum = 0;

if (operator.equals("sum"))
{
   finalNum = (x + y);
}
else if (operator.equals("difference"))
{
   finalNum = (x - y);
}   
else if (operator.equals("product"))
{
   finalNum = (x * y);
}
else if (operator.equals("remainder"))
{
   finalNum = (x % y);
}

System.out.print ("The " + operator + " of your two integers is " + finalNum + ".");

答案 1 :(得分:2)

使用 operator.equals(“sum”)而不是 operator ==“sum”

答案 2 :(得分:0)

有几点:

  • 当您在 if-statements 中编写int finalNum时,您实际在做的是创建一个新变量并为其赋值。但是,此变量的范围仅存在于特定的 if-block 中。因此,您没有看到外部 finalNum 变量得到更新。

  • 考虑使用equalsIgnoreCase(String anotherString)来比较用户的输入是总和,差异,产品还是余数。这是因为在您的情况下,如果用户输入 sum或SUM或Sum ,您将不会感到困扰,理想情况下它们的含义相同。