I am trying to build a calculator that works with JButtons for numbers and arithmetic operands. Every time a JButton is clicked, a String variable (textin) is updated and passed as the parameter of a non-Editable JTextField.The JTextField displays the number that is going to be passed in as a parameter for calculation.When an operand is clicked, the next number should reset the JTextField(i.e. "678+" when 4 is clicked the JTextField should reset to "4").The problem is that it does this EVERY time, regardless of the presence of "+".A fragment of the code follows.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Gui extends JFrame {
private JButton but1;
private JButton but6;
private JButton plus;
private JButton equal;
private JTextField text;
public static String textin;
public double num1;
public double num2;
public String operand;
public Gui() {
super("Calculator");
setLayout(new FlowLayout());
textin = "";
num1 = 0;
num2 = 0;
but1 = new JButton("1");
but6 = new JButton("6");
plus = new JButton("+");
equal = new JButton("=");
operand = "";
text = new JTextField(20);
text.setEditable(false);
add(text);
add(but6);
add(but1);
add(equal);
add(plus);
but1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
textin += "1";
text.setText(textin);
}
});
but6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if(textin.length()!=0&&textin.substring(textin.length()-1)!="+"){
textin += "6";
text.setText(textin);
textin = "6";
text.setText(textin);
} else {
textin = "6";
text.setText(textin);
}
}
});
plus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
num2 = Double.parseDouble(textin);
num1 = num1 + num2;
textin += "+";
text.setText(textin);
operand = "+";
}
});
equal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if(tel == "+") {
num2 = Double.parseDouble(textin);
num1 = num1+num2;
JOptionPane.showMessageDialog(null,String.format("%f",num1));
} else {
JOptionPane.showMessageDialog(null,String.format("error"));
}
}
});
}
}
but1 is a plain button , whereas but6 is a button that should reset the JTextField only after a +.Unfortunately, it resets it EVERY time. I deleted the rest of the code for simplicity.The problem is probably in the if statement of the but6 JButton.Only what exists within else is executed.It doesn't actually check if "+" exists or not.Could someone explain why this happens?