Pregunta

I need to set the current price of several Stocks but I don't know how. I know I should do something like stocksymbol.setPrice() but it's not working. and then I need to "print each stock's information by passing each Stock variable to System.out.println(). This will automatically call the stock's toString() method." And I'm not sure how it's going to call the toString. Help please?

public class Stock {

    private String symbol;
    private String name;
    private double previousClosingPrice;
    private double currentPrice;

    public void Stock(String symbol, String name, double previousClosingPrice {
        this.symbol= symbol;
        this.name =name;
        this.previousClosingPrice = previousClosingPrice;
    }

    public void setPrice(String symbol,double a) {
        this.symbol=symbol;
        currentPrice=a;
    }

    public double getChangePercent() {
        double percentageDiff=100 * (currentPrice - previousClosingPrice) / previousClosingPrice;
        return percentageDiff;
    }

    public String toString() {
        return symbol+" "+name+" "+previousClosingPrice+" "+currentPrice;
    }


    public void main(String[] args) {
        // TODO Auto-generated method stub

        Stock("JAVA","Sun Microsystems, Inc.",4.5);
        Stock("GOOG","Google Inc.",1007.95);
        Stock("AAPL","Apple Inc.",512.49);

        setPrice("JAVA",4.35);

        System.out.println();
    }
}
¿Fue útil?

Solución

There's a lot to be fixed in there.

You need to call all non-static methods on Stock instances. First, you need to create one. Your constructor is broken: one should be declared as public Stock instead of public void Stock - the first is a constructor, the latter is a void method that's (misleadingly) called Stock.

Once you've done that, you can create an instance:

Stock s = new Stock(...arguments here...);

and use that to set price:

s.setPrice(5.12);

Printing s automatically calls ìts toString:

System.out.println(s);

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top