【问题标题】:Why can't my program use my assigned string operator to calculate the two integers? [duplicate]为什么我的程序不能使用我分配的字符串运算符来计算两个整数? [复制]
【发布时间】:2012-09-22 15:48:10
【问题描述】:

可能重复:
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 ".");
    }
}

【问题讨论】:

  • 您需要使用.equals() 而不是== 来比较字符串。另见How do I compare strings in Java?
  • finalNum "." 那怎么编译?
  • 检查你的变量范围。作为您的任何 if/else if 语句中的 finalNum 与 if 条件之前定义的语句不同,并且与病房之后打印的语句不同。
  • 您也可以使用java.util.Scanner 代替BufferedReader + parseInt。这会让你的代码更干净。

标签: java


【解决方案1】:

您需要在此处删除 if 语句中的 int 声明。同样在比较字符串时使用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 + ".");

【讨论】:

  • 嘿,我在程序中走得更远了,但仍然有一个错误。错误:变量 finalNum 可能尚未初始化。这可能意味着什么?
  • 您需要分配本地值finalNum,类似于我上面所做的方式。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    几点:

    • 当您在 if 语句 中编写 int finalNum 时,您实际上是在创建一个新变量并为其分配一个值。然而,这个变量的范围只存在于那个特定的 if-block 中。因此,您不会看到外部 finalNum 变量得到更新。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-25
      • 2017-09-06
      • 1970-01-01
      • 2015-01-27
      • 2022-01-01
      • 2016-12-30
      • 1970-01-01
      • 2020-01-27
      相关资源
      最近更新 更多