0

I'm having some problems automatically populating two arrays using for loop. I know how to do it manually but it's obviously not the right way. now the code looks like that:

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

as you can see there are two arrays, one needed to be populated with string and the other with int. I'm using two constructors the get the string (getCode) and the int (getPrice). So how do I build the loop correctly?

1
  • "some problems" what problems? Commented Dec 4, 2013 at 12:52

2 Answers 2

3

Yea obviously it doesn't look good. Try this :

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

And if possible try to fetch Stock object in Array only. You can use ArrayList collection too.

Sign up to request clarification or add additional context in comments.

Comments

1

I would pass through Lists:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.