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?
First, you should be testing one value at a time (since you return one boolean). Second, you should short circuit and return the first time the number is divisible. Otherwise you'll return true because you reset the value of prime. Finally, Java method names start with a lower case letter (by convention). And, your method only tests for evenness. I think you wanted something like
public static boolean isPrime(int val)
{
for(int i = 2; i < (val / 2); i++)
{
if(val % i == 0)
return false;
}
return true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With