Sorry for such a question, but I just can't get through to it why the following code is not working as it is supposed to.
As written in the title, a user should enter an integer for the code to check if it's prime. If it is not, the user gets to enter an other int, but max 5 times.
I think the primality check is working, but what bothers me is the recursion, because it prints out too much when first given a not-prime number and then a prime.
I hope somebody could explain to me why it is that way... :)
Here is the code:
import java.util.Scanner;
public class Task6v5 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an int: ");
int a = scan.nextInt();
int counter = 0;
isPrime(a, counter, scan);
}
public static void isPrime(int a, int counter, Scanner scan) {
boolean prime;
do {
if (a <= 1) {
counter = counter + 1;
System.out.println("Int to small. Enter a bigger one."
+ " Counter: " + counter);
a = scan.nextInt();
isPrime(a, counter, scan);
} else if (a == 2) {
prime = true;
} else if (a % 2 == 0) {
counter = counter + 1;
System.out.println("This int is even, "
+ "but not a 2. "
+ "Enter an other int."
+ " Counter: " + counter);
a = scan.nextInt();
isPrime(a, counter, scan);
}
for (int i = 2; i <= Math.sqrt(a); i++) {
if (a % i == 0) {
//System.out.println("Are we there?");
//isPrime = false;
counter = counter + 1;
System.out.println("This int is not a prime. "
+ "Enter an other int. Counter: " + counter);
a = scan.nextInt();
isPrime(a, counter, scan);
}
}
prime = true;
System.out.println("This is a prime.");
} while (counter <= 5 && prime == false);
}
}
I get this output for example:
Enter an int:
1
Int to small. Enter a bigger one. Counter: 1
4
This int is even, but not a 2. Enter an other int. Counter: 2
5
This is a prime.
This is a prime.
This int is not a prime. Enter an other int. Counter: 2