gpt4 book ai didi

java - 如何在 Stock 类中进行用户定义输入

转载 作者:行者123 更新时间:2023-12-01 09:20:03 27 4
gpt4 key购买 nike

我在程序中执行用户定义方法时遇到问题,如果有人能帮助我就好了

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());
}
}

这是我的另一个类

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;

}

我似乎无法在我的主目录中针对此问题进行用户输入:

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

还有这个:

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

请帮忙,

最佳答案

您可以使用java.util.Scanner类来获取用户的输入。在主函数中声明 Scanner 变量:

Scanner scan = new Scanner(System.in);

然后使用 scan.nexDouble() 获取用户的输入。例如:

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

关于java - 如何在 Stock 类中进行用户定义输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40224708/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com