Below is a simple Java program that prompts the user to enter two integers and then calculates the number of prime numbers between these two integers. It includes the necessary validations, such as ensuring that the first number is less than or equal to the second number.
Here is the complete Java code:
import java.util.Scanner;
public class PrimeCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the two numbers
System.out.println("Enter the first number:");
int start = scanner.nextInt();
System.out.println("Enter the second number:");
int end = scanner.nextInt();
// Ensure the first number is less than or equal to the second number
if (start > end) {
int temp = start;
start = end;
end = temp;
}
// Count primes between the two numbers
int primeCount = countPrimesInRange(start, end);
// Output the result
System.out.println("Number of prime numbers between " + start + " and " + end + ": " + primeCount);
}
// Method to count primes in a given range
private static int countPrimesInRange(int start, int end) {
int count = 0;
for (int num = start; num <= end; num++) {
if (isPrime(num)) {
count++;
}
}
return count;
}
// Helper method to determine whether a number is prime
private static boolean isPrimitivePrime(int number) {
if (number <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
// Correct implementation of prime checking to replace the incorrect one above
private static boolean isPrime(int number) {
if (number <= 1) {
return false;
}
for (int i = 2; i * i <= number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
Key Components of the Program:
-
Input Handling:
- The program first takes two integers from the user.
- It swaps the numbers if necessary to ensure the range is valid (lower bound to upper bound).
-
Prime Number Calculation:
- Using the
countPrimesInRange method, it iterates through each number between the specified bounds and checks if each number is prime using the isPrime method.
-
Prime Check:
- The
isPrime method determines if a given number is prime. It considers numbers less than 2 as non-prime and checks divisibility up to the square root of the number for efficiency.
-
Output:
- Finally, the program outputs the count of prime numbers found in the specified range.
Make sure you have properly set up your Java development environment to run this code, and you can input the required integers to see how many prime numbers exist between them.