Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package palidromecheck;
- import java.io.*;
- public class PalidromeCheck {
- // global scanner object for each of use when getting user inputs
- private static final java.util.Scanner KB = new java.util.Scanner(System.in);
- // Main method
- public static void main(String[] args) {
- try {
- String[] testCases = LoadStrings("TestCases.txt");
- System.out.println("Evaluating test cases:");
- for(String test : testCases) System.out.println("Word: " + test + "\nResult: " + (Palindrome(test) ? "PASSED" : "FAILED") + " \n");
- } catch (IOException ex) {
- System.out.println("There was a problem loading the test cases, Continuing without testing cases...");
- }
- while(true){ // infinte loop for user tests
- System.out.println("Type a word to test:");
- System.out.println("Result: " + (Palindrome(KB.nextLine()) ? "PASSED" : "FAILED") + " \n");
- }
- }
- // Read the text file twice (since lists arent allowed in this assignment) returns line by line
- private static String[] LoadStrings(String location) throws FileNotFoundException, IOException{
- int count = 0;
- File file = new File(location);
- BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
- while(null != bufferedReader.readLine()) count++;
- bufferedReader = new BufferedReader(new FileReader(file));
- String[] strings = new String[count];
- for(int i = 0; i < count; i++) strings[i] = bufferedReader.readLine();
- return strings;
- }
- // Method to check whether an input string is a palindrome
- private static boolean Palindrome(String test, int... index){
- if(test.length() < 2) return false; // If the string is empty return false (an empty string is not a palindrome)
- if(index.length == 0) index = new int[]{(int)(test.length() / 2)}; // Calculates the distance from middle of input string to its ends
- if(index[0] < 0) return true; // return true if the distance is less than 0 (ends of input string reached)
- return (test.charAt(index[0]) == test.charAt(test.length() - index[0] - 1)) && Palindrome(test, new int[]{index[0] - 1});
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement