You are on page 1of 2

1 /*

2 * Title: hw2_3.java
3 * Abstract: Program checks if an input string is a palindrome or not.
4 * Name: Javier Gonzalez
5 * ID: 1218
6 * Date: 11/09/2021
7 */
8
9 import java.util.*;
10
11 public class hw2_3 {
12
13    public static void main(String[] args) {
14        Scanner sc = new Scanner(System.in);
15
16        String input, output;
17        char[] charArray;
18        int start, end;
19        boolean isPalindrome;
20
21        // System.out.println("Enter a string input:");
22        input = sc.nextLine();
23        // Removes all non-alphanumeric characters & capitalizes input
24        input = input.toUpperCase().replaceAll("[^A-Z0-9]", "");
25        // Creates char array from input string
26        charArray = input.toCharArray();
27        // Initializes start and end indexes
28        start = 0;
29        end = charArray.length - 1;
30        // Calls recursive palindrome method to determine if input is
palindrome
31        isPalindrome = palindrome(charArray, start, end);
32        // Converts boolean isPalindrome to uppercase string
33        output = Boolean.toString(isPalindrome).toUpperCase();
34        // Outputs TRUE/FALSE
35        System.out.println(output);
36   }
37    
38    // Recursive method used to determine if the input (charArray) is a
palindrome
39    private static boolean palindrome(char[] charArray, int start, int end) {
40        if (start >= end) // base case
41            return true;
42        else if (charArray[start] != charArray[end]) // not a palindrome
43            return false;
44        else {
45            start++;
46            end--;
47            return palindrome(charArray, start, end); // recursive call
48       }
49   }
50 }
51
52

You might also like