Advertisement
TizzyT

PalindromeCheck -TizzyT

Mar 28th, 2018
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.26 KB | None | 0 0
  1. package palidromecheck;
  2.  
  3. import java.io.*;
  4.  
  5. public class PalidromeCheck {
  6.     // global scanner object for each of use when getting user inputs
  7.     private static final java.util.Scanner KB = new java.util.Scanner(System.in);
  8.     // Main method
  9.     public static void main(String[] args) {
  10.         try {
  11.             String[] testCases = LoadStrings("TestCases.txt");
  12.             System.out.println("Evaluating test cases:");
  13.             for(String test : testCases) System.out.println("Word: " + test + "\nResult: " + (Palindrome(test) ? "PASSED" : "FAILED") + " \n");
  14.         } catch (IOException ex) {
  15.             System.out.println("There was a problem loading the test cases, Continuing without testing cases...");
  16.         }        
  17.         while(true){ // infinte loop for user tests
  18.             System.out.println("Type a word to test:");
  19.             System.out.println("Result: " + (Palindrome(KB.nextLine()) ? "PASSED" : "FAILED") + " \n");
  20.         }
  21.     }
  22.     // Read the text file twice (since lists arent allowed in this assignment) returns line by line
  23.     private static String[] LoadStrings(String location) throws FileNotFoundException, IOException{
  24.         int count = 0;
  25.         File file = new File(location);
  26.         BufferedReader bufferedReader = new BufferedReader(new FileReader(file));        
  27.         while(null != bufferedReader.readLine()) count++;        
  28.         bufferedReader = new BufferedReader(new FileReader(file));
  29.         String[] strings = new String[count];            
  30.         for(int i = 0; i < count; i++) strings[i] = bufferedReader.readLine();
  31.         return strings;
  32.     }
  33.     // Method to check whether an input string is a palindrome
  34.     private static boolean Palindrome(String test, int... index){        
  35.         if(test.length() < 2) return false; // If the string is empty return false (an empty string is not a palindrome)        
  36.         if(index.length == 0) index = new int[]{(int)(test.length() / 2)}; // Calculates the distance from middle of input string to its ends
  37.         if(index[0] < 0) return true; // return true if the distance is less than 0 (ends of input string reached)
  38.         return (test.charAt(index[0]) == test.charAt(test.length() - index[0] - 1)) && Palindrome(test, new int[]{index[0] - 1});
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement