String Index Out Of Bound Exception error

Posted by Fd Fehfhd on Stack Overflow See other posts from Stack Overflow or by Fd Fehfhd
Published on 2012-10-28T22:37:43Z Indexed on 2012/10/28 23:01 UTC
Read the original article Hit count: 178

Filed under:

Im not really sure why a am getting this error. But here is my code it is meant to test palindromes disregarding punctuation. So here is my code

import java.util.Scanner;

public class PalindromeTester
{
public static void main(String [] args)
{

    Scanner kb = new Scanner(System.in);

    String txt = "";
    int left;
    int right;
    int cntr = 0;

    do
    {
        System.out.println("Enter a word, phrase, or sentence (blank line to stop):");
        txt = kb.nextLine();

        txt = txt.toLowerCase();
        char yP;
        String noP = "";

        for (int i = 0; i < txt.length(); i++)
        {
            yP  = txt.charAt(i);
            if (Character.isLetterOrDigit(txt.charAt(yP)))
            {
                noP += yP;
            }
        }
        txt = noP;

        left = 0;
        right = txt.length() -1;

        while (txt.charAt(left) == txt.charAt(right) && right > left)
        {
            left++;
            right--;
        }

        if (left > right)
        {
            System.out.println("Palindrome");
            cntr++;
        }
        else
        {
            System.out.println("Not a palindrome");
        }
    }

    while (!txt.equals(""));

        System.out.println("You found " + cntr + " palindromes. Thank you for using    palindromeTester.");
    }
}

And if i test it and then i put enter so it will tell me how many palindromes you found the error i am getting is javav.lang.StringIndexOutOfBoundException : String index out of range 0 at PalindromeTester.main(PalindromeTester.java:38) and line 28 is

    while (txt.charAt(left) == txt.charAt(right) && right > left)

Thanks for the help in advance

© Stack Overflow or respective owner

Related posts about java