-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path042-Prime-Number.java
More file actions
86 lines (64 loc) · 2.49 KB
/
Copy path042-Prime-Number.java
File metadata and controls
86 lines (64 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
* ============================================================================
* Program Name : Prime Number
* File Name : 042-Prime-Number.java
* Class Name : PrimeNumber
*
* Description:
* This program accepts an integer from the user and checks whether
* the given number is a Prime Number or not using the for loop.
*
* Objective:
* - Understand user input using the Scanner class.
* - Learn how to find the factors of a number.
* - Determine whether a number is prime.
*
* Author : Shaik Mahaboob Basha
* Repository : 01-Core-Java
* Folder : 08-Java-Programs
* ============================================================================
*/
import java.util.Scanner;
public class PrimeNumber {
// The main() method is the entry point of every Java application.
public static void main(String[] args) {
// Create a Scanner object to read input from the keyboard.
Scanner scanner = new Scanner(System.in);
// Ask the user to enter a number.
System.out.print("Enter a Number: ");
// Read the number entered by the user.
int number = scanner.nextInt();
// Declare and initialize a variable to count the factors.
int factorCount = 0;
// Check whether the entered number is valid.
if (number <= 1) {
// Display that the number is not prime.
System.out.println(number + " is Not a Prime Number.");
// Example Output:
// 1 is Not a Prime Number.
} else {
// Find the factors of the given number.
for (int i = 1; i <= number; i++) {
// Check whether the current number is a factor.
if (number % i == 0) {
// Increase the factor count.
factorCount++;
}
}
// Check whether the number has exactly two factors.
if (factorCount == 2) {
// Display that the number is a Prime Number.
System.out.println(number + " is a Prime Number.");
// Example Output:
// 13 is a Prime Number.
} else {
// Display that the number is not a Prime Number.
System.out.println(number + " is Not a Prime Number.");
// Example Output:
// 12 is Not a Prime Number.
}
}
// Close the Scanner object to release system resources.
scanner.close();
}
}