-1

Im working on a program that uses a class of stocks. one of the methods should calculate the current value of the stock. the instructions say "number of shares times current price". i have a method that updates the price by multiplying this current value by a random percentage. after running the program the value returned by getCurrentValue would be the same as the initial value, that is it never changes. i then changed the variable of currentPrice to static and now the value of currentValue changes but the answers it returns is really high. something along the lines of 3.7E18. having initially set up the currentPrice to 100.

is there something wrong in my code or maybe the instructions are wrong? i don't really know how stocks are valued.

heres some of my code:

private static double currentPrice; 

public void updatePrice(){
    double multiplier = 1.05 + new Random().nextGaussian() * 0.25;
    currentPrice = getCurrentValue() * multiplier;
}

public double getCurrentValue(){
    double currentValue = numShares * currentPrice;
    return currentValue;
}
cee
  • 9
  • 2
  • 7

1 Answers1

0

Your current value is total value for whole stock. And you use this value to determine new price. That's double multiplication of the price and volume. Remove volume from multiplication and you will have reasonable price. Also currentPrice should belong to actual stock and not be one variable for all stocks. So it shouldn't be static.

class Stock {
  private double currentPrice=1; 

  public void updatePrice(){
    double multiplier = 1.05 + new Random().nextGaussian() * 0.25;
    currentPrice *= multiplier;
  }

  public double getCurrentValue(){
    double currentValue = numShares * currentPrice;
    return currentValue;
  }
}
Alex
  • 4,457
  • 2
  • 20
  • 59