0

Please consider the following code:

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));
            }
        }
    }

What is the reason that despite the variable button_press being set to the name of an array object outside of the second IF (nested) loop, the test condition variable math_button[h].getText()is always passed to the calc.Math method?

Is the variable of the button_press string being overridden by the nested IF statement?

obious
  • 609
  • 8
  • 21
  • 33
  • 2
    Use `String#equals` to compare Strings. `==` compares object references – Reimeus Jul 28 '13 at 18:27
  • Luiggi, I see you point about the possible duplication but I never would have found, or even thought of, asking about string comparisons. – obious Jul 28 '13 at 18:41
  • @obious - The reason it's a dupe here is that the (ever popular) SO question about comparing a `String` in Java is the actual problem / error, and any answer to this question will simply be the same answer. – Brian Roach Jul 28 '13 at 18:58
  • Noooooooooooo !!!!!! =''''( – Maroun Jul 28 '13 at 19:44

1 Answers1

1

Use String#equals() as

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

Equals == operator only compares the references with each other; not the actual text content.

EDIT :

The reason equals() didn't work is because the button name is Equals (notice the s)

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

Hence, your if condition should actually be

if(math_button[h].getText().equals("Equals")) {
Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89