Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

recursion palindrome method... i'm stuck

$
0
0
Hi everyone. So in my Introduction to Java class, we're doing recursive methods. My homework was to figure out a way to use Scanner, arrays, and a recursion to figure out whether a user-inputted String is a palindrome or not. So far my code is:
public static boolean palindrome () {
    Scanner ask = new Scanner(System.in);
    System.out.println("This is a program for determining whether a user input is a palindrome. Please enter your input.");
    String input = ask.nextLine();
    String lowercase = input.toLowerCase(); 
    String revised = lowercase.replace(" ","");
    char [] charArray = revised.toCharArray();
    int length = charArray.length;
    if (length == 1)
      return true;
    if (length == 2 && charArray[0] == charArray[length])
      return true;
    if (charArray[0] != charArray[length])
      return false;
    else 
      palindrome();
    return true;
  } 


When I run the code with the word "noon" which is a palindrome, I get:
 java.lang.ArrayIndexOutOfBoundsException: 4
	at Recursion.palindrome(Recursion.java:92)
	at Recursion.main(Recursion.java:6)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272) 


How can I fix this?

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>