Ace Shafiq Ace Shafiq - 1 month ago 15
Java Question

How to make an user-defined input in Class Stock

I'm having trouble doing a user-defined method in my program here, would it be nice if anyone can help me

package Ex_9_2;



public class TestStock {
public static String price;

//main
public static void main(String[] args) {

Stock stock = new Stock("ORCL", "Oracle Corporation");

System.out.println("Please enter previous closing price ");
stock.setPreviousClosingPrice(34.5);

System.out.println("Please enter current price ");
stock.setCurrentPrice(34.35);
System.out.println(stock);

// Display stock info
System.out.println("Previous Closing Price: " + stock.getPreviousClosingPrice());
System.out.println("Current Price: " + stock.getCurrentPrice());
System.out.println("Price Change: " + stock.changePercent());
}
}


Here's my other class

package Ex_9_2;

public class Stock {
private String symbol;
private String name;
private double previousClosingPrice;
private double currentPrice;

public Stock() {
}

public Stock(String symbol, String name) {
this.symbol = symbol;
this.name = name;
}

public String getSymbol() {
return this.symbol;
}

public String getName() {
return this.name;
}

public double getPreviousClosingPrice() {
return previousClosingPrice;
}

public double getCurrentPrice() {
return currentPrice;
}

public void setSymbol(String symbol) {
this.symbol = symbol;
}

public void setName(String name) {
this.name = name;
}

public void setPreviousClosingPrice(double price) {
this.previousClosingPrice = price;
}

public void setCurrentPrice(double price) {
this.currentPrice = price;
}

public double changePercent() {
return (currentPrice - previousClosingPrice) / previousClosingPrice;
}

@Override
public java.lang.String toString(){
return "\nYour Company's name is " + this.name
+ "\nYour Company's Symbol is " + this.symbol;

}


I can't seem to make a user-input in my main for this problem:

System.out.println("Please enter previous closing price ");
stock.setPreviousClosingPrice(34.5);


and this:

System.out.println("Please enter current price ");
stock.setCurrentPrice(34.35);


please help,

Answer

You can use java.util.Scanner class to take inputs from the user. Declare a Scanner variable in your main function:

Scanner scan = new Scanner(System.in);

Then use scan.nexDouble() for taking input from the user. For example:

System.out.println("Please enter previous closing price ");
stock.setPreviousClosingPrice(scan.nextDouble());
Comments