So i have this calculator (on Java) and when i press a button i wanna check if in the JTextField(pantalla) is only "0" so i can replace it with the number instead of concatenate the button i pressed... the thing i´ve noticed is that when i try it, it returns false everytime
i´ve tried to save the .getText() into a String variable and then compare it to the literal "0", i even try to put the text to "0" 1 line above the comparation with the .setText().
pantalla = new JTextField();
pantalla.setHorizontalAlignment(SwingConstants.RIGHT);
pantalla.setBounds(72, 19, 144, 25);
contentPane.add(pantalla);
pantalla.setColumns(10);
pantalla.setText("0");
JButton btn0 = new JButton("0");
btn0.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
pantalla.setText("0");
System.out.println(pantalla.getText() == "0");
// pantalla.setText(pantalla.getText() + btn0.getText());
}
});
heres the output of the code ive just shown: image(https://i.sstatic.net/g62Sp.png)
When you compare a content of the strings, you should use equals()
instead of ==
(that compares the objects' references). Read more here and here
So, change your code:
System.out.println(pantalla.getText() == "0");
to
System.out.println("0".equals(pantalla.getText()));
and you will get the desired result.