avoiding code redundancies for a calculation in Java
You can use a +1
or -1
coefficient based on isBuying
value.
newPrice = Math.round((stock.getPrice() + (isBuying ? 1.0 : -1.0) * roundRandomNumber * 0.1 * amount) * 100) / 100.00;
You could try by extracting just the factor in the condition:
public void changePrice(Stock stock, int amount, boolean isBuying) {
double roundRandomNumber = Math.round((0.5 + Math.random()) * 100) / 100.00;
double newPrice;
//calculates plus or minus depending on the buyoption
double factor;
if (isBuying) {
factor = 1.0
} else {
factor = -1.0
}
newPrice = Math.round((stock.getPrice() + (factor * roundRandomNumber) * 0.1 * amount) * 100) / 100.00;
if (newPrice > 0 && newPrice < 3000) {
stock.setPrice(newPrice);
}
}