I have this code:
public class TestPrimaryArray
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter 5 numbers: ");
int[] numbers = new int[5];
for(int i = 0; i < numbers.length; i++)
{
numbers[i] = scan.nextInt();
boolean isPrime = PrimeArray(numbers);
System.out.println("Is " +numbers[i]+ " a prime? " +isPrime);
}
}
public static boolean PrimeArray(int[] arr)
{
boolean prime = true;
for(int i = 1; i < arr.length; i++)
{
if(arr[i]%2 == 1)
prime = true;
else
prime = false;
}
return prime;
}
}
This program is suppose to take input from the user place it into a one dimensional array of 5, and then tell whether the numbers are prime or not. I run my code and it compiles and everything, but when I see the results it does not give me the right answer. Here is an example run with the numbers 11 7 3 5 20
Enter 5 numbers:
11 7 3 5 20
Is 11 a prime? false
Is 7 a prime? false
Is 3 a prime? false
Is 5 a prime? false
Is 20 a prime? false
It is suppose to tell me that all of them except 20 are true. I do not know what I am doing wrong. What should I do?
PrimeArraytake an array if you call it for each input? And have you noticed, that you set the variableprimefor each number of the passed array and return its value after the loop? So it is quite clear that it can only return the result of the last entry of your array. So please rething thePrimeArraymethod.PrimeArrayeach time? Use first for loop to populate the array. Use second for loop in primeArray to print the output.