在java中计算和显示数字

时间:2012-03-23 14:21:25

标签: java swing bigdecimal

我有以下代码......

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());

每次单击一个按钮时,textArea_price和textArea_quantity中的数字将相乘并显示在textArea_result中。我希望textArea_result中的值被添加到两个textareas的乘法结果中,而不是每次单击按钮时都重置textArea_result中的值...

2 个答案:

答案 0 :(得分:1)

我不懂Java但不是这个吗?

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语句尝试这个,但它只是语法糖:

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));

答案 1 :(得分:0)

或者:

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));

或者:

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());