FatmaTurk
FatmaTurk

Reputation: 83

calculating and displaying numbers in java

I have the following code....

double num1 = Double.parseDouble(textArea_price.getText());
double num2 = Double.parseDouble(textArea_quantity.getText());

double result = num1*num2;
textArea_result.setText(
    new BigDecimal(textArea_price.getText())
        .multiply(new BigDecimal(textArea_quantity.getText())).toString());

Everytime a button is clicked the numbers in textArea_price and textArea_quantity is multiplied and displayed in textArea_result. I want the value in textArea_result to be added onto the result of the multiplication of the two textareas rather than resetting the value in textArea_result every time the button is clicked...

Upvotes: 0

Views: 657

Answers (2)

Jordan
Jordan

Reputation: 9911

I don't know Java but wouldn't it be this?

double num1 = Double.parseDouble(textArea_price.getText());

double num2 = Double.parseDouble(textArea_quantity.getText());

double oldResult = 0;
String result = textArea_result.getText();
if (result  != "")
    oldResult = Double.parseDouble(result);

double result = oldResult + num1 * num2;
textArea_result.setText(Double.toString(result));

If you really want to avoid if statements try this, but it is just syntactical sugar:

double num1 = Double.parseDouble(textArea_price.getText());

double num2 = Double.parseDouble(textArea_quantity.getText());

String result = textArea_result.getText();
double oldResult = (result == "") ? 0 : Double.parseDouble(result);

double result = oldResult + num1 * num2;
textArea_result.setText(Double.toString(result));

Upvotes: 1

barsju
barsju

Reputation: 4446

Either:

double num1 = Double.parseDouble(textArea_price.getText());
double num2 = Double.parseDouble(textArea_quantity.getText());
double oldres = Double.parseDouble(textArea_result.getText());

double result = oldres + num1*num2;
textArea_result.setText(Double.toString(result));

Or:

BigDecimal price = new BigDecimal(textArea_price.getText());
BigDecimal quantity = new BigDecimal(textArea_quantity.getText());
BigDecimal oldTotal = new BigDecimal(textArea_result.getText());

BigDecimal total = price.multiply(quantity).add(oldTotal);
textArea_result.setText(total.toString());

Upvotes: 0

Related Questions