0

可能重复:
如何比较 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 ".");
    }
}
4

3 回答 3

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 + ".");
于 2012-09-22T15:50:41.653 回答
2

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

于 2012-09-22T15:50:43.230 回答
0

几点:

  • 当您int finalNumif 语句中编写时,您实际上在做的是创建一个新变量并为其分配一个值。但是,此变量的范围仅存在于该特定if 块中。因此,您不会看到外部finalNum变量得到更新。

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

于 2012-09-22T15:54:55.630 回答