• Post Reply Bookmark Topic Watch Topic
  • New Topic

for enhanced for ArrayList: method get  RSS feed

 
Dana Ucaed
Ranch Hand
Posts: 406
6
Netbeans IDE Oracle Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Ranchers,

I am stuck with the code:



countPrimes contains prime numbers.

Enhanced for that traverse ArrayList begins with element at position 2.

So countPrimes.get(0) returns 2, but when I traverses ArrayList numbers 2, 3 aren't displayed.

What is the reason?



 
Dana Ucaed
Ranch Hand
Posts: 406
6
Netbeans IDE Oracle Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
and at the end of program I get:

at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.get(ArrayList.java:411)
at calculateprimes.CalculatePrimes.main(CalculatePrimes.java:49)


Thanks a lot.

 
Dana Ucaed
Ranch Hand
Posts: 406
6
Netbeans IDE Oracle Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I write:



My output is good and without exception.

Indeed initial for begins with i = 2.
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Create a List of ten prime numbers on paper, with indices and values. Hint: at index 0 will be the value 2, then 3, 5, etc.
Now go through that List with the for‑each loop you wrote in line 43; when you get to the entry index 5, what will your i be? Now find the entry corresponding to countPrimes.get(i). Does that explain why you are suffering an Exception? By the way: you only posted the bottom of the stack trace; nest time please scroll up and find the top of the stack trace, which will provide you with useful information.
You are writing for loops incorrectly. If you are not suffering an Exception, I am very surprised about that.

I suggest you find a better name for the List than countPrimes; it doesn't count them but records them. Maybe primeNumbers would be a better name.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!