我是一个编程新手,所以请多多包涵。我搜索并找不到可以回答这个问题的现有线程。我编写了以下代码,该代码应该根据安全对象是被用户识别为股票还是债券来吐出 stock.toString() 或 bond.toString() 罐头短语。但是,我收到“无法解决安全性”编译器错误。我想这是一个问题,因为安全对象的类不是在编译时定义的。真的吗?如果是这样,有什么办法可以在不诉诸反射方法的情况下解决这个问题?谢谢!
public static void main(String[] args) {
double thePrice;
double theShares;
double theEarnings;
double theRate;
String securityType;
Scanner in = new Scanner(System.in);
System.out.println("Is it a stock or a bond?");
securityType = in.nextLine();
if (securityType.compareToIgnoreCase("stock") == 0) {
System.out.println("Successfully set to STOCK");
System.out.println("What are the earnings?");
theEarnings = in.nextDouble();
Stock security = new Stock();
security.setEarnings(theEarnings);
}
else if (securityType.compareToIgnoreCase("bond") == 0) {
System.out.println("Successfully set to BOND");
System.out.println("What is the rate?");
theRate = in.nextDouble();
Bond security = new Bond();
security.setRate(theRate);
}
System.out.println("What is the price");
thePrice = in.nextDouble();
System.out.println("How many shares are there?");
theShares = in.nextDouble();
security.setPrice(thePrice);
security.setShares(theShares);
System.out.println(security);
}
感谢@Jigur Joshi、@penartur 和其他人。这是我们提出的解决方案,但如果有更好的选择,请告诉我。如果securityType既不是“股票”也不是“债券”,我正在添加一个else语句来清理:)
public static void main(String[] args) {
...
Security security = null;
String securityType;
Scanner in = new Scanner(System.in);
System.out.println("Is it a stock or a bond?");
securityType = in.nextLine();
System.out.println("What is the price");
thePrice = in.nextDouble();
System.out.println("How many shares are there?");
theShares = in.nextDouble();
if (securityType.compareToIgnoreCase("stock") == 0) {
System.out.println("Successfully registered STOCK");
security = new Stock();
System.out.println("What are the earnings?");
theEarnings = in.nextDouble();
((Stock) security).setEarnings(theEarnings);
}
if (securityType.compareToIgnoreCase("bond") == 0) {
System.out.println("Successfully registered BOND");
security = new Bond();
System.out.println("What is the rate?");
theRate = in.nextDouble();
((Bond) security).setRate(theRate);
}
security.setPrice(thePrice);
security.setShares(theShares);
System.out.println(security);
}