So for school I need to make a GUI calculator, I have fully made the calculator working, but only up to single digit arthmatic (1 1) but now I wish to make it that that I can have multiple digits inputed (123 45) this is my code:
b1.addActionListener(e -> {System.out.println("Response:1 was inputed onto calculator");
if(arth == "") {
num1S = Double.toString(num1);
Tnum1S = "1" num1S;
num1 = Double.parseDouble(Tnum1S);
l.setText(Tnum1S);
Tnum1S = "";
} else {
num2S = Double.toString(num2);
Tnum2S = num2S "1";
num2 = Double.parseDouble(Tnum2S);
l.setText(Tnum2S);
Tnum2S = "";
}});
//T at the start means Temporary, S at te end means a String, normally my numbers are set to double.
This is a screenshot of my results from my try of making this work does anyone know how to make it that the number is not added into the decimal places?
CodePudding user response:
Maybe this is what you want:
DecimalFormat format = new DecimalFormat("#.#"); // you can change it here
System.out.println(format.format(d));
CodePudding user response:
If you take a look at the line Tnum1S = "1" num1S;
, you are essentially concatenating 1 to the content of num1S as a String. Instead, for building a calculator you should be adding them as doubles and then push to the user interface.
num1S contains the String equivalent of num1.
num1S = Double.toString(num1);
Tnum1S now gets a 1 concatenated with num1S.
Tnum1S = "1" num1S;
You are now converting the concatenated value ( not added value )back to Double
num1 = Double.parseDouble(Tnum1S);
You are finally setting it on the UI.
l.setText(Tnum1S);
Instead you should,
- Convert the numbers of your interest from String to Double.
- Perform the operation as a Double.
- Push the result back to the user interface as a String.
In short, in your case, you are using the concatenation operation on String rather than the addition operation on a double.