Reputation: 49
Alright, so I have this problem where you can glitch to get more than you actually pay for. It's kind of hard to explain, when you increase the amount, well first of all here's my code:
public void setAmount(Player player, int button) {
int amount = (Integer) player.getTemporaryAttribute("geAmount");
int id = (Integer) player.getTemporaryAttribute("geItem");
int price = (Integer) player.getTemporaryAttribute("price");
long totalPrice = price * amount;
switch(button) {
case 157:
if(player.getRights() > 1){
player.sm(""+totalPrice+"");
}
if(amount > 1) {
amount--;
} else {
amount = 1;
}
break;
case 159:
if(player.getRights() > 1){
player.sm(""+totalPrice+"");
}
if(amount < Integer.MAX_VALUE && totalPrice <= Integer.MAX_VALUE && totalPrice >= 0) {
amount++;
}
break;
case 162:
if(player.getRights() > 1){
player.sm(""+totalPrice+"");
}
if(player.getTemporaryAttribute("buying") == Boolean.TRUE && totalPrice <= Integer.MAX_VALUE && totalPrice >= 0) {
amount += 1;
} else {
amount = 1;
}
break;
case 164:
if(player.getRights() > 1){
player.sm(""+totalPrice+"");
}
if(player.getTemporaryAttribute("buying") == Boolean.TRUE && totalPrice <= Integer.MAX_VALUE && totalPrice >= 0) {
amount += 10;
} else {
amount = 10;
}
break;
case 166:
if(player.getRights() > 1){
player.sm(""+totalPrice+"");
}
if(player.getTemporaryAttribute("buying") == Boolean.TRUE && totalPrice <= Integer.MAX_VALUE && totalPrice >= 0) {
amount += 100;
} else {
amount = 100;
}
break;
case 168:
if(player.getRights() > 1){
player.sm(""+totalPrice+"");
}
if(player.getTemporaryAttribute("buying") == Boolean.TRUE && totalPrice <= Integer.MAX_VALUE && totalPrice >= 0) {
amount += 1000;
} else {
amount = player.getInventory().getContainer().getNumberOff(id);
}
break;
case 171:
case 173:
if(player.getRights() > 1){
player.sm(""+totalPrice+"");
}
player.getActionSender().sendConfig(1111, (Integer) player.getTemporaryAttribute("price"));
break;
}
if(amount == 0){
amount = 1;
}
if(amount >= Integer.MAX_VALUE || amount < 0) {
amount = Integer.MAX_VALUE;
}
player.setTemporaryAttribute("geAmount", amount);
player.getActionSender().sendConfig(1109, id);
player.getActionSender().sendConfig(1110, amount);
}
The total price is what keeps overflowing, but I am unsure of how to make it stop. Someone had suggested using something like this:
int last = 0;
int current = 0;
while(last < current) //loop terminates on overflow
last = current++;
But I don't know how I would use that in this code. Could anyone help me please?
Upvotes: 0
Views: 144
Reputation: 1
Initialise your total to zero...Similar program. Go to http://codejava.co.uk/download_code.html
Upvotes: 0
Reputation: 310884
long totalPrice = price * amount;
Cast price
or amount
to long
so the calculation is carried out as a long:
long totalPrice = (long)price * amount;
Upvotes: 0
Reputation: 5661
Use the BigInteger
class
http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigInteger.html
Upvotes: 2