本文介绍了添加2个BigDecimal值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class Point {
BigDecimal x;
BigDecimal y;
Point(double px, double py) {
x = new BigDecimal(px);
y = new BigDecimal(py);
}
void addFiveToCoordinate(String what) {
if (what.equals("x")) {
BigDecimal z = new BigDecimal(5);
x.add(z);
}
}
void show() {
System.out.print("\nx: " + getX() + "\ny: " + getY());
}
public BigDecimal getX() {
return x;
}
public BigDecimal getY() {
return y;
}
public static void main(String[] args) {
Point p = new Point(1.0, 1.0);
p.addFiveToCoordinate("x");
p.show();
}
}
好的,我想添加2个BigDecimal值.我正在使用带有double的构造函数(因为我认为这是可能的-文档中有一个选项).如果我在主类中使用它,我会得到:
Ok, I would like to add 2 BigDecimal values. I'm using constructor with doubles(cause I think that it's possible - there is a option in documentation). If I use it in main class, I get this:
x: 1
y: 1
当我使用System.out.print显示我的z变量时,我得到了:
When I use System.out.print to show my z variable i get this:
z: 5
推荐答案
BigDecimal是不可变的.每个操作都会返回一个包含操作结果的新实例:
BigDecimal is immutable. Every operation returns a new instance containing the result of the operation:
BigDecimal sum = x.add(y);
如果您想更改x,则必须这样做
If you want x to change, you thus have to do
x = x.add(y);
阅读 javadoc 确实有助于理解类及其方法如何工作.
Reading the javadoc really helps understanding how a class and its methods work.
这篇关于添加2个BigDecimal值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!