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!