-2

I wanted to make a simple prime number printer in java, and the last for loop was giving me an error.

import java.util.ArrayList;
public class Main {
 public static void main(String[] args) {
  ArrayList<Integer> primeNumbers = new ArrayList<Integer>();
  primeNumbers.add(1);
   for (int i = 2; true; i++){
    for(int j = 2; j <= i; j++){
     double a = i/j;
     if(a % 1 == 0 && i != j) primeNumbers.add(i);
    }
   }
   for (int value : primeNumbers) {
       System.out.println(value);
   }
 }
}

Why is this happening?

  • It's just the last for loop that is giving me the error – Roei Burstein Jun 04 '15 at 00:12
  • This is the comment section. People are not always looking at this, so do not expect instant responses. Now about your code... What is the error and can you post the stack trace if there is one? – Forseth11 Jun 04 '15 at 00:15
  • `for (int i = 2; true; i++){` you have the boolean part of the for loop set as true and no where inside your loop do you have a break. Therefore you loop will go forever and it will never exit and go onto the printing for loop. – Forseth11 Jun 04 '15 at 00:16
  • This is because your `first` loop never terminates. – fukanchik Jun 04 '15 at 00:16

2 Answers2

2

Because the outer for loop is infinite (that is the last loop is unreachable). Change this

for (int i = 2; true; i++) { // <-- infinite loop

to something like

for (int i = 2; i < 1000; i++) { // 2 to 1000.
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • ok, now that I fixed it, my new code is import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList primeNumbers = new ArrayList(); primeNumbers.add(1); for (int i = 2; true; i++) { for (int j = 2; j <= i; j++) { double a = i / j; if (a % 1 == 0 && i != j) { primeNumbers.add(i); System.out.println(primeNumbers.get(i)); } } } } } It still gives me an error though, and it says: Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 2 – Roei Burstein Jun 04 '15 at 00:27
  • @RoeiBurstein Because you tried to get the element at the index 3, even thought the list had only two elements in it. – user253751 Jun 04 '15 at 00:32
0

It's because you are trying to refer to primeNumbers, that is an ArrayList<Integer> with an int. It should be:

for (Integer value : primeNumbers) {
                System.out.println(value);
            }

Integer it's different than int. Look at this:

What is the difference between an int and an Integer in Java and C#?

Community
  • 1
  • 1
Francisco Romero
  • 12,787
  • 22
  • 92
  • 167
  • no it's not. look for something called "autoboxing" – fukanchik Jun 04 '15 at 00:19
  • @fukanchik I saw it now. Thanks for correct me! I'm learning Java and I didn't know that but I have a doubt, could be some problems attached to this "autoboxing"? I mean, it wouldn't preferable to use `Integer` instead of `int` and then not to force to the compiler to translate it? – Francisco Romero Jun 04 '15 at 00:28