Search code examples
javaif-statementfor-looparraylisttoarray

finding the prime numbers of an arraylist with toArray, prints wrong


I have a method for finding the prime number from a list of numbers using ArrayList and toArray. The majority of the code works, except for the fact that when I'm printing the parameters 1 and 10, it prints 1,2,3,5,7. So it prints the prime numbers between 1 and 10, but it also prints 1. I think the error is in the first or second for-loop, but I'm not sure.

public int primtall(int a, int b) {
    ArrayList<Integer> primtallene = new ArrayList<>();
    int primtall = 0;
    int største;
    int minste;
    if(a == b){ 
        primtall = 0;
    }
    else {
        if(a > b) {
            største = a;
            minste = b;
        } 
        else if (a < b){
            minste = a;
            største = b;


        for(int i = minste; i <= største; i++) {
            boolean isPrime = true;
            for (int j = 2; j < i; j++) {
                if (i % j == 0) { 
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {

                primtall = i;
                primtallene.add(primtall);
            }
        }
    }

  }

  Integer[] numrene = new Integer[primtallene.size()];
  numrene = primtallene.toArray(numrene);
  for(Integer nummer : numrene){
      System.out.println("Primtall = " + nummer);
    }
    return 0;
}

Dont mind the last return value, I only added that because BlueJ requires me to.

Can anyone help with identifying the error in the code?

Thanks in advance!


Solution

  • That's becuase of the below for loop:

    for (int j = 2; j < i; j++) {
        if (i % j == 0) { 
            isPrime = false;
            break;
        }
    }
    

    For the first time, i will be 1, which would make j < i condition return false and hence, control won't go into this for loop.

    Due to this, isPrime will be true and 1 will get added into the list. To prevent this, you can just check whether i >= 2 in subsequent if condition, e.g.

    if (isPrime && i >= 2) {
        primtall = i;
        primtallene.add(primtall);
    }
    

    Also, if you don't want to return any value from this method, you can change the return type as void and remove return statement.