• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to use ArrayLists in a program.  RSS feed

 
Sunali Anu
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please see the code below and I am trying to change the program to use ArrayLists instead of Arrays. When i changed the program to use ArrayLists, the program stops after reading the how many number of weeks?

Not sure wh? Please help..

public class TstAr {

/**
* @param args
*/
public static void main(String[] args) {


System.out.println("Give me no.of bands?");
int num = Keyboard.readInt();
TstAr[] ta = new TstAr[num];

for (int i=0;i<ta.length;i++)
{
System.out.println("Name of Band" + (i+1));
String n = Keyboard.readString();
ArrayClass ac = new ArrayClass(n);
ta[i] = ac;
}

System.out.println("How many weeks of sales?");
int numWks = Keyboard.readInt();

for (int i=0;i<ac.length;i++)
{
for (int j=0;j<numWks;j++)
{
System.out.println("How many boxes did BandBooster # " + (i+1) + "sell for week number " + (j+1));
int numBoxes = Keyboard.readInt();
ac[i].updateSales(numBoxes);
}
}



for (int i=0;i<ac.length;i++)
{

//toString
System.out.println(ac[i].toString());
}



}

}
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since it's your changes break the program, you'd have to show us your changes
if you want to know why they break the program! Just seeing the working version doesn't help us at all.
 
Sunali Anu
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Below is the code i changed it to use Array lists, the code after the while loop doesn't get executed and directly goes to the end of while loop to ask me the question if i have more bands to calculate? Not sure why? please suggest..


[ EJFH: Added "[CODE ]" tags. ]
[ June 11, 2007: Message edited by: Ernest Friedman-Hill ]
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Notice that your loop is based on the value of the size of the list.
 
Sunali Anu
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How else can i tell the loop to scan through the Array List?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look carefully at your code. You are creating an empty ArrayList:

ArrayList al = new ArrayList();

Then you have a for-loop for all elements in the list:

for (int i=0;i<al.size();i++)

Since the list is empty (it has 0 elements), the loop is not executed. Nowhere in your code you are putting something in the ArrayList - it remains empty.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!