java - Strange String out of Bounds exception -



java - Strange String out of Bounds exception -

i working on method test if phrase palindrome. method takes string , checks if first , lastly letters of string same. if so, takes away letters , checks string 1 time again until there 1 (or zero) letter left using recursive function.

string start = s.substring(0, 1); string end = s.substring(s.length() - 1, s.length());

takes first , lastly letter of each string; however, if utilize 2 letter string string index out of bounds error. thought changing index 0,0 help later realized doesn't grab first letter. there no issue string 1 or more 2 characters long. i'll set rest of method below if y'all need it, programme doesn't run far 2 letter string.

public static boolean palindrometester(string s){ s = justletters(s); //calls method removes spaces, punctuation string start = s.substring(0, 1); string end = s.substring(s.length() - 2, s.length()-1); if(s.equals("") || s.length() == 1){ homecoming true; } else if(start.equalsignorecase(end)){ homecoming palindrometester(s.substring(1, s.length() - 1)); } else{ homecoming false; } }

woohoo! found it! in first example, method created substrings after each recursive call, regardless if string empty or not, generating indexoutofbounds exception each empty string. creating substrings after checking empty string, programme won't create substrings if string empty.

old:

string start = s.substring(0, 1); string end = s.substring(s.length() - 2, s.length() - 1); if (s.equals("") || s.length() == 1) { homecoming true; }

new:

if (s.equals("") || s.length() == 1) { homecoming true; } string start = s.substring(0, 1); string end = s.substring(s.length() - 1);

feels figure own stuff out.

java string indexoutofboundsexception

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -