File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import java .util .InputMismatchException ;
2+ import java .util .Scanner ;
3+
4+ /**
5+ * To check whether a given number is prime
6+ */
7+ public class PrimeCheck {
8+
9+ public static void main (String [] args ) {
10+
11+ // Accept input from the console
12+ System .out .print ("Please enter a natural number: " );
13+ int num = 0 ;
14+ try {
15+ Scanner sc = new Scanner (System .in );
16+ num = sc .nextInt ();
17+ sc .close ();
18+ } catch (InputMismatchException e ) {
19+ outputAndEnd ("Input not valid, expected a natural number." ); // Error message for all non numerical inputs
20+ }
21+
22+ if (num < 0 ) {
23+ outputAndEnd ("Input not valid, natural number expected" ); // Error message for all negative inputs
24+ } else if (num < 2 ) {
25+ outputAndEnd ("0 and 1 are neither prime nor composite" ); // Info message for 0 and 1
26+ }
27+
28+ // Check if the given number is divisible from any number between 2 and num/2, if so, its composite
29+ for (int i = 2 ; i <= num / 2 ; i ++) {
30+ if (num % i == 0 ) {
31+ outputAndEnd (num + " is not a prime number." ); // Output result and exit as we found one divisor other than 1 and itself
32+ }
33+ }
34+ // The number has exit the loop with no divisors, which means it is a prime number, print success message.
35+ outputAndEnd (num + " is a prime number." );
36+ }
37+
38+ // A method to print the given message and exit the program
39+ private static void outputAndEnd (String message ) {
40+ System .out .println (message ); // output the given message
41+ System .exit (0 ); // exit the program
42+ }
43+ }
You can’t perform that action at this time.
0 commit comments