Reputation: 2188
heres the code I need help with.
if (itemAmount >= usedWithAmount) {
for (int i = 0; i < 10; i++) {
if (amountToTransfer == 6) {
usedWithAmount = i;
break;
}
amountToTransfer = itemAmount - i;
System.out.println(amountToTransfer);
}
} else if (itemAmount < usedWithAmount) {
for (int i = 0; i < 10; i++) {
if (amountToTransfer == 6) {
itemAmount = i;
break;
}
amountToTransfer = usedWithAmount - i;
}
}
Alright, people couldn't understand the first time, so I'll go more in depth.
This is used for in my game you have potions. The potions have an amount in them. A potion with (6) at the end, has 6 doses left, (5) has 5 doses left, etcetc.
I'm making it so when you use a potion on another one, it transfers the doses from the potion to the other potion to make it full.
So lets say I have a potion with 5 doses left(represented as itemAmount), and I use it on another potion which has 2 doses left(represented as usedWithAmount).
What I want the algorithm above to do, is use the value of the first potion(itemAmount), and find out how many doses it should transfer to the other potion to make it full(6 doses = full).
So if I used the 5 dose potion with the 2 dose potion, the 5 dose potion should lose 4 doses, while the 2 dose potion gets 4 doses, I want the amountToTransfer(in this case is 4) to represent how many doses to remove from the first item, and to be added to the second item.
Upvotes: 0
Views: 856
Reputation: 29646
See my comment. You can solve this very easily using Math.min
.
amountToTransfer = Math.min(itemAmount, 6 - usedWithAmount);
This will return whichever is smaller -- the remainder of the source potion or the amount needed to fill the target potion.
This can also be rewritten:
final int space = 6 - usedWithAmount;
amountToTransfer = itemAmount < space ? itemAmount : space;
or, similar to how David wrote it,
final int space = 6 - usedWithAmount;
if (itemAmount < space) {
amountToTransfer = itemAmount;
} else {
amountToTransfer = space;
}
Upvotes: 2
Reputation: 1419
How about:
// Figure out how much room is available in the one getting the transfer
amountMissing = 6 - usedWithAmount
// If it has room to hold everything, transfer it all
if (amountMissing >= itemAmount)
{
amountToTransfer = itemAmount;
}
// Otherwise, transfer as much as it can hold
else
{
amountToTransfer = amountMissing;
}
Upvotes: 1