私はプログラミング初心者ですので、ご容赦ください。この質問に答えることができる既存のスレッドを検索しましたが見つかりませんでした。次のコードを記述しました。これは、セキュリティオブジェクトがユーザーによって株式または債券として識別されたかどうかに基づいて、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が「stock」でも「bond」でもない場合にクリーンアップする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);
}