Tyl*_*uur 2 java stack-overflow integer max
我正在研究交换系统,用户正在设置交换的价格和金额.
我想确保交换不超过整数最大值,但我遇到了问题.
当交换金额达到9或更多时,即使我检查确保该数字不大于最大值,它也不起作用.我做了一些调试,当设置金额为9而价格为2,147,483,646(比最大数量少1)时,它打印出来:
2,147,483,630 - 9
这是我的调试代码,我应该添加什么来确保不会发生这种情况?
public void setPrimaryAmount(int primaryAmount) {
int price = primaryAmount * this.price;
System.out.println(Misc.format(this.price * primaryAmount) + " - " + primaryAmount);
if (price > Integer.MAX_VALUE ||
price == Integer.MAX_VALUE ||
price >= Integer.MAX_VALUE ||
price < 0 || price <= 0 ||
price++ == Integer.MAX_VALUE) {
System.out.println("Attempted to set a bad amount.");
return;
}
this.primaryAmount = primaryAmount;
}
Run Code Online (Sandbox Code Playgroud)
"尝试设置不良金额"打印输出,直到您输入金额> = 9.
您不能将值存储在int中,然后检查它是否对于int来说太大了.把它存放在一个很长的位置.
long price = (long)primaryAmount * (long)this.price;
Run Code Online (Sandbox Code Playgroud)