I'm a beginner to Java and am having trouble figuring out what's wrong with my code here. I get an error message that says my method must return a result of type int[], but am not sure how to proceed. Essentially, what I'm trying to do in the distanceFromA method is take each character of a string, get its distance from the letter 'a' in the alphabet as an integer, and insert that integer into a 5-integer array in the order the characters appear in the string. What am I missing?
import java.util.Arrays;
public class WordDistances {
public static int[] distanceFromA(String word) {
if (word.length() == 0) {
int[] error = {0,0,0,0,0};
return error;
}
if (word.length() > 0) {
int[] testArray = new int[5];
String wordL = word.toLowerCase();
testArray[Math.abs(word.length()-5)] = (int)wordL.charAt(0) - (int)'a';
return testArray;
}
}
public static void main(String[] args) {
System.out.print(Arrays.toString(distanceFromA("abcde")));
}
}
I haven't learned how to use for loops yet, and am trying to complete it without using one, but all of the tutorials I've found unfortunately use them.
EDIT: The string must be 5 characters, and I do have to use recursion exclusively (no loops or just doing it 5 times, unfortunately).
if (word.length() > 0)
? Code returns if length is zero; otherwise, if not zero, it can only be greater than zero; 2) no need for (neither) casting in(int)wordL.charAt(0) - (int)'a'
- the casting is automatic for subtraction