I have got a java code that checks for prime numbers and then it displays them. However, there are some instances when there are no prime numbers (e.g between 14 - 17). In those cases I want a single message to appear. For example "No primes found"
. I don't know how to add this to my code.
This is my whole class:
import java.io.*;
public class Prime {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
public static int lowerBound;
public static int higherBound;
public void getInput() throws IOException {
System.out.println("Please enter the lower and upper bound");
String line1 = input.readLine();
String line2 = input.readLine();
int lowInput = Integer.parseInt(line1);
int highInput = Integer.parseInt(line2);
lowerBound = lowInput;
higherBound = highInput;
}
public void validatedata() throws IOException {
do {
getInput();
if (lowerBound < 2) {
System.out.println("Finish");
break;
} else if (higherBound < lowerBound) {
System.out
.println("The upper bound should be at least as big as the lower bound.");
}
} while (higherBound < lowerBound);
}
public void prime_calculation() throws IOException {
while ((lowerBound >= 2) && (higherBound > lowerBound)) {
int k;
for (k = lowerBound; k < higherBound; k++) {
boolean primecheck = true;
for (int j = 2; j < k; j++) {
if (k % j == 0) {
primecheck = false;
}
}
if (primecheck)
System.out.println(k);
}
validatedata();
}
}
}
And this is my main void method:
import java.io.IOException;
public class PrimeUser extends Prime {
public static void main(String argv[]) throws IOException {
Prime isprime = new Prime();
isprime.validatedata();
isprime.prime_calculation();
}
}
Have a look at http://rosettacode.org/wiki/Miller-Rabin_primality_test#Java which explains how to determine whether a number is a prime.
And then work over your array of values and keep a flag whether a number is a prime or not.