【问题标题】:Arrays and if Statements: Array object not passable into if statement [duplicate]数组和 if 语句:数组对象不能传入 if 语句 [重复]
【发布时间】:2013-07-28 18:26:08
【问题描述】:

请考虑以下代码:

public JButton math_button[] = new JButton[5];
    for (int h = 0; h <math_button.length; h++) {
        if(event.getSource()==math_button[h]) {
            String button_press = math_button[h].getText();     
            if(math_button[h].getText().equals("Equals")) {
                secondn = Integer.parseInt(math_input.getText());
                System.out.println(firstn + " math operator " + secondn + " and "+ math_button[h].getText());
                System.out.println(calc.Math(button_press, firstn, secondn));
            } else {
                firstn = Integer.parseInt(math_input.getText());
                //math_input.setText("");
                //placeholder = calc.Math(math_button[h].getText(), firstn, secondn);
                //int secondn = Integer.parseInt(math_input.getText());
                //int result = calc.Math(math_button[h].getText(), firstn, secondn);
                //math_input.setText(Integer.toString(firstn));
                //math_input.setText(Integer.toString(placeholder));
            }
        }
    }

尽管变量button_press被设置为第二个IF(嵌套)循环之外的数组对象的名称,但测试条件变量math_button[h].getText()总是传递给calc.Math方法的原因是什么?

button_press 字符串的变量是否被嵌套的 IF 语句覆盖?

【问题讨论】:

  • 使用String#equals 比较字符串。 == 比较对象引用
  • Luiggi,我看到你指出了可能的重复,但我从来没有发现,甚至没有想过,询问字符串比较。
  • @obious - 这是一个骗局的原因是关于在 Java 中比较 String 的(曾经流行的)SO 问题是实际的问题/错误,并且这个问题的任何答案都只是相同的答案。
  • Nooooooooooooo !!!!!! =''''(

标签: java arrays if-statement


【解决方案1】:

String#equals() 用作

if(math_button[h].getText().equals("Equal")) {

Equals == 运算符仅将引用相互比较;不是实际的文本内容。

编辑

equals() 不起作用的原因是按钮名称为Equals(注意s

public String[] name = {"Add", "Mulitply", "Divide", "Subtract", "Equals"};

因此,您的if 条件实际上应该是

if(math_button[h].getText().equals("Equals")) {

【讨论】:

  • 虽然您的答案是正确的,但问题和解决方案已在可能的 dup 问题中说明。
  • 谢谢,但我已经尝试过您的建议,但没有奏效。
  • @obious 检查更新。您缺少s
  • 我注意到了,并相应地更改了它,但它仍然不起作用
  • @obious 你能在if 之前添加一个println() 并检查实际的字符串吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 2016-07-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多