Hy there i a beginner in java started 3 weeks ago, im having some problems with this code.
in the main method i have an array containing 10 elements.
i’ve already made several methods to like
public static void println(int[] array) —— to print and array
public static boolean isPrime(int el) ———– prime test. returns true or false
public static int countPrimes(int[] array) — returns back the number of primes in the array.
this is the array
int[] array = new int{7,5,7,2,11,-4,5,,10,2}
the method im having problems with is:
public static int[] primesInArray(int[] array)
{
int n = array.length;
int[] temp = new int[countPrimes(array)];
int j = 0;
for(int i = 0; i < n; i++)
{
if(isPrime(array[i]))
{
temp[j] = array[i];
j= j +1;
}
}
return temp;
}
it should return an array of 7 numbers like this {7,5,7,2,11,5,2}
but instead i get the original array back.
what am i doing wrong.
What is the purpose of this test?
array[i] % array[i]will always be 0 so your test always returns True.Shouldn’t you instead use the following?
Edit:
And as Ravi points out, you don’t ever use your temp array! I think you need to change
array[i] = array[j];totemp[j] = array[i];when the correctediftest is True.