This discussion is archived
2 Replies Latest reply: Nov 18, 2012 5:36 PM by rp0428 RSS

Where my output went south...

974869 Newbie
Currently Being Moderated
So I guess my toString() is screwed up, & I'm not sure how to fix it.
My call in main to toString():
String Goog;
String Google;
Stock firstStock = new Stock();
Stock secondStock = new Stock("Goog", "Google");
secondStock.setPreviousClosingPrice(20000);
secondStock.setCurrentPrice(40000);
System.out.println("Stock info: " + secondStock.toString());
System.out.println("Stock 1 percent change: " + firstStock.getChangePercent()
+ " Stock 2 precent change: " + secondStock.getChangePercent());

toString method:
public String toString(Stock symbol, Stock name, Stock currentPrice){
symbol.toString();
name.toString();
currentPrice.toString();
return toString();
}

Output:

run:
Please enter symbol:
orc
Please enter name:
OracleCorp
Please enter previous closing price greater than 0:
12000
Please enter the current price:
15000
Stock info: Stock@72f60f20
Stock 1 percent change: 0.25 Stock 2 precent change: 1.0
BUILD SUCCESSFUL (total time: 11 seconds)


I'm obviously returning something that isn't working. Not sure how to set this up my toString method should:
//toString method returns a String representation of the Stock object
//append the symbol, name, and current price of the stock

Not sure if my call is bad, or my method is doing something nasty, any help would be great :)))

Thank you!
  • 1. Re: Where my output went south...
    rp0428 Guru
    Currently Being Moderated
    >
    toString method:
    public String toString(Stock symbol, Stock name, Stock currentPrice){
    symbol.toString();
    name.toString();
    currentPrice.toString();
    return toString();
    }
    >
    You need to review the basics about objects and review that doc link from your other thread about the method of the Object base class.

    Your code says you are passing three instances of the Stock class to your procedure. So your procedure is not being called anywhere in your code. The code above is doing a 'toString' call to those instances but you aren't saving the result of the call anywhere so those three lines really don't do anything anyway.

    The built-in 'toString' method is doing what it is designed to do. If you want to do something different you need to override the 'toString' method and have it do something different. Then a myStock.toString will call your method.

    Search the web for 'java tutorial tostring' and you will see plenty of tutorials on how to do that.
  • 2. Re: Where my output went south...
    974869 Newbie
    Currently Being Moderated
    Sweet, yeah I'm not sure why I was doing that. Fixed it up!

    public String toString(){      
    return "Symbol:" + symbol + " Name:" + name + " Current Price:" + currentPrice;
    }

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points