Goo day
I am doing a Swing application for a calculator as an exercise. The problem I have is with the actual numbers display in the text field. The idea I had was to have a String value of say “1” for example and then every time the number one button is clicked to concatenate the value of “1” to the initial and then to parse the String value to Double so that one can work with the value.
private void butOneActionPerformed(java.awt.event.ActionEvent evt) {
String one;
Double doubleOne;
if(operandOne.equals("0."))
{
one = "1";
operandOne = ".";
one += operandOne;
txtDisplay.setText(one);
}
else
{
operandOne = "1";
one = txtDisplay.getText();
one += operandOne;
txtDisplay.setText(one);
}
doubleOne = Double.parseDouble(one);
}
Is there a perhaps another more effective way to do this. The fact that one needs to work with a floating point number makes it a bit trickey.
There’s nothing wrong with the way you’ve done it, other than I would make the parsing of the double ‘lazy’; i.e. don’t convert the String to a double until a calculation is required, and get rid of the
doubleOnefield.