user2904796 user2904796 - 2 years ago 128
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));
for(int j=0;j<listOfWordsToCheck.size();j++) {
String secondWord= listOfWordsToCheck.get(j);
if(firstWord.startsWith(secondWord)==true) {
else if(firstWord.startsWith(secondWord)==false);
if(indexPositions.size()==0) {
return "Yes";
else if(indexPositions.size()!=0) {
return "No,"+indexPositions.get(0)+"";

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download