Results 1 to 3 of 3
  1. #1
    Hotsawwce is offline Member
    Join Date
    Nov 2012
    Posts
    1
    Rep Power
    0

    Default Palindrome testing program. String error

    I keep getting an error saying: Exception in thread"main" java.lang.StringIndexOutOfBoundsException: String index out of range: 109
    at java.lang.String.charAt(unknow source)
    at test.main(test.java:23)

    Here is my code:

    Java Code:
    import java.util.Scanner;
    public class test
    {
    
    	public static void main (String[] args)
    	{
    
    		
    		Scanner input = new Scanner(System.in);
    		
    		
    			String palTest = input.next();
    			
    	
    
    		int test = palTest.length()-1;
    		char firstChar, lastChar;
    		char first = palTest.charAt(0);
    		char last = palTest.charAt(test);
    		while (first<last)
    		{
    		
    		firstChar = palTest.charAt(first);
    		lastChar = palTest.charAt(last);
    		
    		if(firstChar == lastChar)
    		{
    		first++;
    		last--;
    		}
    		
    		}
    		System.out.println();
    		if (first < last)
    		System.out.println("k");
    		else 
    		System.out.println("wtf");
    		}
    		}
    I don't seem to get the problem if the string is only one char long. But I can't seem to find my mistake.


    *edit* It seems to work with numbers only actually >_>
    Last edited by Hotsawwce; 11-03-2012 at 06:20 PM.

  2. #2
    arieltal is offline Member
    Join Date
    Sep 2012
    Posts
    34
    Rep Power
    0

    Default Re: Palindrome testing program. String error

    Java Code:
     firstChar = palTest.charAt(first);
            lastChar = palTest.charAt(last);
    here you use first and last, which are CHARS, not int location in the string..
    think the problem starts here.

  3. #3
    SJF
    SJF is offline Senior Member
    Join Date
    Oct 2012
    Posts
    108
    Rep Power
    0

    Default Re: Palindrome testing program. String error

    As arieltal pointed out:
    String.charAt(int i) NOT String.charAt(char c) ..... Java is doing an implicit typecast of char to int.... (int)'n' = 110

Similar Threads

  1. Palindrome Program
    By e.cummins95 in forum New To Java
    Replies: 7
    Last Post: 03-09-2012, 12:59 AM
  2. Replies: 7
    Last Post: 05-03-2011, 06:41 PM
  3. Palindrome program
    By trinity in forum New To Java
    Replies: 4
    Last Post: 04-16-2011, 03:22 AM
  4. How to count number of palindrome in a string??
    By i4ba1 in forum Advanced Java
    Replies: 5
    Last Post: 04-12-2011, 12:58 PM
  5. Palindrome program help
    By Nel in forum New To Java
    Replies: 1
    Last Post: 03-03-2011, 03:49 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •