We're just starting recursion in my Java class, and I'm stuck on one of the homework problems.
Supposed to write a method that goes through a string and checks to see if it's made up completely of 'alphabetical pairs.' This means, one letter is just as far from a as another letter is from z. For example, 'a' and 'z' would be alphabetical pairs, as 'a' is as far from 'a' as 'z' is from 'z'.
This is what my code looks like:
Code
// Alphabetical Pairs method
//Determine if the given string has pairs of letters at opposite ends of the alphabet, return a boolean
public static boolean alphabeticalPairs(String s){
// If the string has a length of 0, return true
if(s.length() == 0)
return true;
// If the string still has letters left, find out the first letter's distance from A, this is the variable 'd'
else{
int d = s.charAt(0) - 'a';
// The character we're looking for, wanted, will be just as far from z as the first character was from a.
// If we take the int value for 'z' and subtract from it the distance from 'a' to first character, we have the target ascii value
int wanted = 'z' - d;
for(int i = 1; i < s.length(); i++){ // Iterate through each character (except the first) in the string s
if(s.charAt(i) == wanted){ // If the current character matches the wanted ascii value, cut it and the first character out
String newString = s.substring(1,i) + s.substring(i+1);
alphabeticalPairs(newString); // Recursively call the method on the new string
}
}
return false;
}
}
I feel like it's probably something wrong in my newString. I'm not very good with manipulating strings to remove single characters.
Everything compiles, I just get false every time unless I input a blank string (so base case works).
Thanks for any help.