I'm trying to program a scientific calculator with a GUI in java and have been able to do everything so far except for the exponent button (x^y).
Here's what I have for the button click event right now but it doesn't work because I can't figure out how to take in two values while only pressing the button one time.
private void btnExponentActionPerformed(java.awt.event.ActionEvent evt) {
for (int i = 0; i < 2; i++)
{
if(i == 0)
{
double x = Double.parseDouble(String.valueOf(tfdDisplay.getText()));
}
else if(i == 1)
{
double y = Double.parseDouble(String.valueOf(tfdDisplay.getText()));
}
tfdDisplay.setText(null);
}
double ops = Math.pow(x, y);
tfdDisplay.setText(String.valueOf(ops));
}
I would like it to take in the value that is currently in the textfield, then have the user click the exponent button, then take in the next value they put in as the actual exponent value, then calculate the answer when they click the "=" button.
I've looked online and found a video that shows how to make a scientific calculator with an exponent button but when I follow his method of coding the button, it does not work correctly. Instead, it just squares what is inside the textfield, rather than letting the user put in their own exponent.
Here's a picture of what the calculator actually looks like for reference.
Thanks in advance!
edit: Here is what I have programmed for the "=" button.
String answer;
secondnum = Double.parseDouble(tfdDisplay.getText());
if(operations == "+")
{
result = firstnum + secondnum;
answer = String.format("%.2f", result);
tfdDisplay.setText(answer);
}
else if(operations == "-")
{
result = firstnum - secondnum;
answer = String.format("%.2f", result);
tfdDisplay.setText(answer);
}
else if(operations == "*")
{
result = firstnum * secondnum;
answer = String.format("%.2f", result);
tfdDisplay.setText(answer);
}
else if(operations == "/")
{
result = firstnum / secondnum;
answer = String.format("%.2f", result);
tfdDisplay.setText(answer);
}
Should I add this to the "=" button?
else if(operations == "^")
{
result = Math.pow(firstnum, secondnum);
answer = String.format("%.2f", result);
tfdDisplay.setText(answer);
}
So I figured out how to solve my problem.
Here is what I put inside the button click event:
private void btnExponentActionPerformed(java.awt.event.ActionEvent evt) {
firstnum = Double.parseDouble(tfdDisplay.getText());
tfdDisplay.setText(null);
operations = "^";
}
and here is what I added to the "=" button click event:
else if(operations == "^")
{
result = Math.pow(firstnum, secondnum);
answer = String.format("%.2f", result);
tfdDisplay.setText(answer);
}
Thank you Obicere!