无法使用for循环填充数组 - java

时间:2013-12-04 12:41:44

标签: java arrays

我遇到一些问题,使用for循环自动填充两个数组。 我知道如何手动完成,但显然不是正确的方法。现在代码看起来像这样:

    Scanner scan = new Scanner(System.in);

     String [] allStockCodes = new String [5];
     int [] stockPrices = new int [5];

     Stock s0 = new Stock ("TEVA", 100);
     Stock s1 = new Stock ("APPLE", 45);
     Stock s2 = new Stock ("GOOGLE", 765);
     Stock s3 = new Stock ("IBM", 76);
     Stock s4 = new Stock ("MICROSOFT", 436);

     allStockCodes[0] = s0.getCode();
     allStockCodes[1] = s1.getCode();
     allStockCodes[2] = s2.getCode();
     allStockCodes[3] = s3.getCode();
     allStockCodes[4] = s4.getCode();


    stockPrices[0] = s0.getPrice();      
    stockPrices[1] = s1.getPrice();   
    stockPrices[2] = s2.getPrice();   
    stockPrices[3] = s3.getPrice();   
    stockPrices[4] = s4.getPrice();  

你可以看到有两个数组,一个需要用字符串填充,另一个用int填充。我正在使用两个构造函数来获取字符串(getCode)和int(getPrice)。 那么我该如何正确构建循环呢?

2 个答案:

答案 0 :(得分:3)

是的,它看起来并不好看。试试这个:

 Stock[] temp = new Stock[]{s0,s1,s2,s3,s4};
     for(int i=0;i<5;i++){
         allStockCodes[i] = temp[i].getCode();
         stockPrices[i] = temp[i].getPrice();        
     }

如果可能,尝试仅在Array中获取Stock对象。您也可以使用ArrayList收藏。

答案 1 :(得分:1)

我会通过列表:

List<Stock> stocks = new ArrayList<Stock>();
stocks.add(new Stock ("TEVA", 100));
stocks.add(new Stock ("APPLE", 45));
stocks.add(new Stock ("GOOGLE", 765));
stocks.add(new Stock ("IBM", 76));
stocks.add(new Stock ("MICROSOFT", 436));

List<String> allStockCodesList = new ArrayList<String>();
List<Integer> stockPricesList = new ArrayList<Integer>();

for (Stock entry: stocks) {
  allStockCodesList.add(enty.getCode());
  stockPricesList.add(entry.getprice());
}