Skip to content

Commit 9fea604

Browse files
Merge pull request utkarsh-shekhar#56 from techpavan/master
Java code to check if a given number is prime.
2 parents 17e8c28 + e938df6 commit 9fea604

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

java/PrimeCheck.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
}

0 commit comments

Comments
 (0)