How do I return a value which was changed in a for loop?

Looking at posts like "How do i return the last generated number in a for loop?", "How do I return a value from within a for loop?", and "Having trouble returning a value outside of a for loop with Java" did not help because the problems described in the posts seem tangent to the post titles.

I am receiving the error: "error: missing return statement".

I am trying to create a word count by first setting the word count to 1. The for loop is to traverse a String sentence. Each time a space is found in the String, word count will increase by 1.

Where do I put a return statement so that the program works as intended? I can’t put a return statement on the outside of the loop because then 1, the initial value of wc, will be returned.

// wc = word count
public static int wordCount(String sentence) {
  int wc = 1;
  for (int a = 0; a <= sentence.length()-1; a++) {
    if (sentence.charAt(a) == ' ') {
      wc += 1;
    }
    if (a == sentence.length()-1) {
      return wc;
    }
  }
}

>Solution :

A method must return a value. In your given code, you only return if a certain condition is met. Otherwise, there is no return value. That’s the issue with your code.

One thing you can do is to break the loop once your condition is met and then return at the end of the method.

public static int wordCount(String sentence) {
  int wc = 1;
  for (int a = 0; a <= sentence.length()-1; a++) {
    if (sentence.charAt(a) == ' ') {
      wc += 1;
    }
    if (a == sentence.length()-1) {
      break;
    }
  }
  return wc;
}

But in your code, you are checking the same condition twice.

First, in your for loop, you are looping from a = 0 to a <= sentence.length()-1.

You can change it to this, to increase the readability of your code:

for (int a = 0; a < sentence.length(); a++) {

What this does is, you start your loop where a = 0 and iterate until a is lesser than the length of the sentence. That is exactly same as "until a is lesser than or equal to the (length of the sentence1)". Check how the explanation of the code is also simpler here.

Then inside your loop, you are checking whether a == sentence.length() - 1 to return. But this is the exact condition your for loop is breaking on.

So, your code can be simplified to the following:

public static int wordCount(String sentence) {
  int wc = 1;
  for (int a = 0; a < sentence.length(); a++) {
    if (sentence.charAt(a) == ' ') {
      wc += 1;
    }
  }
  return wc;
}

If you have no other limitations, you can just use this to count the number of words:

public static int wordCount(String sentence) {
  String[] words = sentence.split(" ");
  return words.length(); 
}

Or, even a one liner like this:

public static int wordCount(String sentence) {
  return sentence.split(" ").length(); 
}

Leave a Reply