-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberListener.java
More file actions
116 lines (93 loc) · 2.3 KB
/
NumberListener.java
File metadata and controls
116 lines (93 loc) · 2.3 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import java.util.Scanner;
public class NumberListener
{
private static void startProgram()
{
Scanner scan = new Scanner(System.in);
printIntro();
while(true)
{
System.out.print("Enter a number: ");
String input = scan.nextLine();
if(isExitCommand(input))
{
endProgram();
break;
}
processInput(input);
}
scan.close();
}
private static void printIntro()
{
System.out.println("Number Analyzer");
System.out.println("Prime, Odd, or Even.");
System.out.println("Type exit to end.\n");
}
private static boolean isExitCommand(String input)
{
return input.equalsIgnoreCase("exit");
}
private static void processInput(String input)
{
try
{
long number = Long.parseLong(input);
displayResult(number);
}
catch(NumberFormatException e)
{
System.out.println("Invalid input!\n");
}
}
private static void displayResult(long number)
{
StringBuilder result = new StringBuilder();
result.append(number).append(" is:\n");
if(isPrime(number))
{
result.append("- Prime\n");
}
if(number % 2 == 0)
{
result.append("- Even\n");
}
else
{
result.append("- Odd\n");
}
System.out.println(result);
}
private static boolean isPrime(long number)
{
if(number <= 1)
{
return false;
}
if(number == 2)
{
return true;
}
if(number % 2 == 0)
{
return false;
}
long limit = (long)Math.sqrt(number);
for(long i = 3; i <= limit; i += 2)
{
if(number % i == 0)
{
return false;
}
}
return true;
}
private static void endProgram()
{
System.out.println("\nProgram Ended. Thank you.");
}
public static void main(String[] args)
{
startProgram();
}
}