Why I am getting: 1)-Infinity for The percent change? 2)previous closing price i
ID: 3531164 • Letter: W
Question
Why I am getting:
1)-Infinity for The percent change?
2)previous closing price is: 34.35 should be new current Price is: 34.35
package stockPrice;
public class Stock { //Set Data fields public String symbol; public String sName; public double previousClosingPrice; public double currentPrice = 0; //Default Constructor public Stock(){ } //Constructor with previous closing price parameter public Stock(String newSymbol, String newSName, double newPreviousClosingPrice) { this.symbol = newSymbol; this.sName = newSName; this.currentPrice = newPreviousClosingPrice; } //Return Percent Change double getChangePercent(){ return (((previousClosingPrice - this.currentPrice)/previousClosingPrice)*100); } //Set a new Current Price double setCurrentPrice(double newCurrentPrice){ this.currentPrice = newCurrentPrice; return this.currentPrice; } @Override public String toString() { // TODO Auto-generated method stub String total = "The symbol is: " + this.symbol + " and the name is: " + this.sName + " and the previous closing price is: " + this.currentPrice; return total; } } Driver:
package stockPrice; public class Driver{ public static void main(String[] args) { //Driver Program for all testing and Instantiation Stock stock1 = new Stock ("ORCL", "Oracle Corporation", 34.5); System.out.println(stock1.toString()); stock1.setCurrentPrice(34.35); System.out.println(stock1.toString() + ". The percent change is: " + stock1.getChangePercent()); } }
Explanation / Answer
well there is an error in your code when you call the function
setCurrentPrice(double newCurrentPrice)
you are not receiving its value, either receive its value or make it void.
now to answer your questions :
1) it might be the problem of the compiler because your code is correct. Try this,
store every operation like substraction, division into different local variables and then
use them.
like:
x=previousClosingPrice - this.currentPrice;
double y = x/previousClosingPrice;
double z = y*100;
return z;
this should solve your problem :), some times compiler goes crazy, lol.
2) According to your code at the end of program :
previous closing price is: 34.5 and new current Price is: 34.35
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.