user2904796 user2904796 - 6 months ago 21
Java Question

Java return statement

Eclipse keeps telling me to add a return statement to the method, even though I did so.

public class PrefixCode {
public String isOne(String[] words) {
if(words.length==1) {
return "Yes";
}
ArrayList<Integer> indexPositions= new ArrayList<Integer>();
for(int i=0;i<words.length;i++) {
String firstWord=words[i];
java.util.List<String> listOfWordsToCheck = new ArrayList<String>(Arrays.asList(words));
listOfWordsToCheck.set(i,null);
for(int j=0;j<listOfWordsToCheck.size();j++) {
String secondWord= listOfWordsToCheck.get(j);
if(firstWord.startsWith(secondWord)==true) {
indexPositions.add(j);
}
else if(firstWord.startsWith(secondWord)==false);
}
}
if(indexPositions.size()==0) {
return "Yes";
}
else if(indexPositions.size()!=0) {
Collections.sort(indexPositions);
return "No,"+indexPositions.get(0)+"";
}
}
}


My return statements are outside of the for loops, so I don't understand what's wrong here.

Answer

There is no default return. The only returns you are making are if some conditions are true. What if the conditions are false?

Add a return after the last else block and you are all good to go.

The else block is redundant. What lies inside the else block should be be without else.

Comments