-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathPalindromCheckerEnhanced.java
More file actions
63 lines (53 loc) · 1.96 KB
/
PalindromCheckerEnhanced.java
File metadata and controls
63 lines (53 loc) · 1.96 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
import java.util.Scanner;
public class PalindromCheckerEnhanced {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Loop to continuously prompt the user for input until they decide to exit.
while (true) {
System.out.print("Enter a word or phrase (or 'exit' to stop): ");
String input = scanner.nextLine();
// Check if the user wants to exit the program.
if ("exit".equalsIgnoreCase(input)) {
break;
}
// Check if the provided string is a palindrome.
if (isPalindrome(input)) {
System.out.println("Yes, it's a palindrome!");
} else {
System.out.println("No, it's not a palindrome.");
}
}
System.out.println("Thanks for using the palindrome checker!");
scanner.close();
}
/**
* Check if a string is a palindrome. A palindrome reads the same forwards and backwards.
*
* @param str the string to check.
* @return true if the string is a palindrome, false otherwise.
*/
static boolean isPalindrome(String str) {
// Clean the string by removing unwanted characters and converting to lowercase.
str = cleanString(str);
int left = 0;
int right = str.length() - 1;
// Loop to compare the characters of the string from the outside in.
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
/**
* Clean the string by removing non-alphanumeric characters and converting to lowercase.
*
* @param str the string to clean.
* @return the cleaned string.
*/
static String cleanString(String str) {
return str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
}
}