I'm in my first semester of programming as a first year college and we were tasked to make a calculator GUI. I'm almost done but I need to make the "Error" appear if the denominator is 0 but it outputs 0.0. My other problem is that I need the gui to restart after showing the final answer but what happens is that after I clicked equals then clicked the number it just continues. So if I press 1+1 then clicked =, it outputs 2 but when I clicked a number for example 1, it just becomes 21.
Also, how do I remove the .0 at the end of every answer? I tried endsWith and replace after every equation but it's not working.
@Override
public void actionPerformed(ActionEvent e){
for(int i=0;i<10;i++) {
if(e.getSource() == numbers[i]) {
text.setText(text.getText().concat(String.valueOf(i)));
}
}
if(e.getSource()==dec) {
if (text.getText().contains(".")) {
return;
} else {
text.setText(text.getText() + ".");
}
}
if(e.getSource()==add) {
num1 = Double.parseDouble(text.getText());
operator ='+';
label.setText(text.getText() + "+");
text.setText("");
}
if(e.getSource()==sub) {
num1 = Double.parseDouble(text.getText());
operator ='-';
label.setText(text.getText() + "-");
text.setText("");
}
if(e.getSource()==mult) {
num1 = Double.parseDouble(text.getText());
operator ='*';
label.setText(text.getText() + "*");
text.setText("");
}
if(e.getSource()==div) {
num1 = Double.parseDouble(text.getText());
operator ='/';
label.setText(text.getText() + "/");
text.setText("");
}
if(e.getSource()==neg) {
Double neg = Double.parseDouble(text.getText());
neg*=-1;
text.setText(String.valueOf(neg));
}
if(e.getSource()==per) {
num1 = Double.parseDouble(text.getText())/100;
label.setText(text.getText() + "%");
text.setText(String.valueOf(num1));
label.setText("");
}
if(e.getSource()==equ) {
num2=Double.parseDouble(text.getText());
switch(operator) {
case'+':
ans=num1+num2;
break;
case'-':
ans=num1-num2;
break;
case'*':
ans=num1*num2;
break;
case'/':
if (num2==0)
text.setText("Error");
else
ans=num1/num2;
break;
}
label.setText("");
text.setText(String.valueOf(ans));
}
}
}
}