存储并打印存储在抽象类的子类的对象数组中的值

问题描述 投票:0回答:1

我还在学习Java,所以请多多包涵。

建立先前的工作。因此,我有一个抽象的Stock类,其中包含ETF类和Dividend类,它们都扩展了Stock类。 ETF和股息从股票中覆盖了calculatePrice。在另一个StockManager类中,我可以输入一些信息,例如股票名称,股价以及ETF值或股息。以前,我将这些输入存储到对象数组中

Stock [] stk =新股票[STOCKLIMIT]

现在,由于Stock是一个抽象类,所以我不能再这样做了。如何存储这些值?或打印出来?

此外,您可以在StockManager中添加,删除,打印或查找库存的总成本。

删除了一些不需要的东西只需要添加,打印和总成本方面的帮助

StockManager类

public class StockManager
{

   Scanner stdin = new Scanner(System.in);

   final int STOCKLIMIT = 6;
   int numberOfStocks = 0;

   Stock[] stk = new Stock[STOCKLIMIT]; //before stock was abstract

   String name;
   Double namePrice;
   int etfDividendVal;


   public void run()
   {
      String command = stdin.next();

      while (!command.equalsIgnoreCase("Q"))
      {
         if (command.equalsIgnoreCase("A"))
         {

            else
            {
               String commandTwo = stdin.next(); //either e for etf or d for dividend

               if (commandTwo.equalsIgnoreCase("E"))
               {
                  name = stdin.next();
                  namePrice = stdin.nextDouble();
                  etfDividendVal = stdin.nextInt();

                  //stk[numberOfStocks] = new Stock(name, namePrice); //object array when stock wasn't abstract

                  //store name, namePrice, and etfDividendVal somewhere now that stock is abstract

                  numberOfStocks++;
               }

               else if (commandTwo.equalsIgnoreCase("D"))
               {
                  name = stdin.next();
                  namePrice = stdin.nextDouble();
                  etfDividendVal = stdin.nextInt();

                  //stk[numberOfStocks] = new Stock(name, namePrice);

                  //where to store name, namePrice, and etfDividendVal somewhere now that stock is abstract

                  Stock stk = new Dividend();
                  numberOfStocks++;
               }
               }
            }
         }


         else if (command.equalsIgnoreCase("R")) //remove a stock
         {
            else
            {
               name = stdin.next();
               namePrice = stdin.nextDouble();

               for (int i = 0; i < numberOfStocks; i++)
               {
                  if (stk[i].getTicker().equals(name))
                  {
                     for(int z = i; z < numberOfStocks; z++)
                     {
                        if (z + 1 == numberOfStocks)
                           stk[z] = null;
                        else
                           stk[z] = stk[z+1];
                     }  
                     numberOfStocks--;
                  }
               }
            }
         }

         else if (command.equalsIgnoreCase("P"))
         {
            else
            {
               // print stock name, price, and etf/divident value
               }
            }
         }

         else if (command.equalsIgnoreCase("C"))
         {
            else
            {
               //print the total cost
            }
         }
      }
   } 
}

抽象股票类

abstract public class Stock
{
   protected String commandTwo;
   protected String ticker;
   protected Double price;
   protected int etfDividendVal;

   public Stock()
// default constructor

   public Stock(String commandTwo, String ticker, Double price, 
                int etfDividendVal)
   {
      this.commandTwo = commandTwo;
      this.ticker = ticker;
      this.price = price;
      this.etfDividendVal = etfDividendVal;
   }


   public String getTicker()
   {
      return ticker;
   }


   public String setTicker(String name)
   {
      ticker = name;
      return ticker;
   }


   public Double getPrice()
   {
      return price;
   }


   public Double setPrice(Double namePrice)
   {
      price = namePrice;
      return price;
   }


   @Override
   public String toString()
   {
      return this.ticker + " " + this.price + "\t";

   }

   public abstract double calculatePrice();
}

ETF类

public class ETF extends Stock
{
   public float numberOfStocks;

   @Override
   public double calculatePrice()
   {
      return (price * numberOfStocks);
   }
}

股息类别

public class Dividend extends Stock
{
   public float yieldPercentage;

   @Override
   public double calculatePrice()
   {
      return (price * yieldPercentage);
   }
}

应该看起来像这样

Pick an option:  A-Add R-Remove   P-Print    C-Total cost     Q-Quit
A
E
AMD
30.45
10
Pick an option:  A-Add R-Remove   P-Print    C-Total cost     Q-Quit
A
D
FXAIX
100
3
Pick an option:  A-Add R-Remove   P-Print    C-Total cost     Q-Quit
P
AMD 30.45 10.0
FXAIX 100.0 0.03
Pick an option:  A-Add R-Remove   P-Print    C-Total cost     Q-Quit
C
The total cost is: 307.4999999329448
java class abstract-class abstract
1个回答
0
投票

您仍然可以创建数组Stock[],因为ETFDividend都扩展了Stock,所以可以将它们添加到数组中。要在从数组中检索的对象上使用ETFDividend中声明的方法,必须像下面这样强制转换它们:ETF etf = (ETF) stk[someIndexHere];。请注意,您不知道哪些对象实际上是ETF,哪些对象实际上是Dividend,如果将它们强制转换为实际上不是的类型,则会收到错误消息。您可以使用stk运算符检查ETF中的对象是Dividend还是instanceof

Stock stock = stk[0]; // Provided that there is a Stock at stk[0]

if (stock instanceof ETF) {
    ETF etf = (ETF) stock;
    // Now you can use etf as an ETF object
} else if (stock instanceof Dividend) {
    // The second if-statement is redundant since there are only
    // two possibilities, but in the future there might be more
    // classes extending Stock
    Dividend div = (Dividend) stock;
    // Now you can use div as a Dividend object
}

尽管ETFDividend均未实现任何新方法,所以不需要强制转换。 instanceof也是,除非您想告诉您的用户他们正在处理哪种股票。

© www.soinside.com 2019 - 2024. All rights reserved.