0

I'm new to Java and training with exercism.io

I don't really know why I get an error (not a statement here). Can you explain why I get this?

/home/zenmoa/snap/exercism/5/exercism/java/raindrops/src/main/java/RaindropConverter.java:13: error: not a statement
            result + pling;
                   ^
/home/zenmoa/snap/exercism/5/exercism/java/raindrops/src/main/java/RaindropConverter.java:17: error: not a statement
            result + plang;
                   ^
/home/zenmoa/snap/exercism/5/exercism/java/raindrops/src/main/java/RaindropConverter.java:21: error: not a statement
            result + plong;

the code =>

class RaindropConverter {

    String convert(int number) 
    {
     String pling = "Pling";
     String plang = "Plang";
     String plong = "Plong";
     String result;
      for (int i = 0;i < 3;i++)
      {
         if(number % 3 == 0 && i == 0)
         {
            result + pling;
         }
         else if (number % 5 == 0 && i == 1)
         {
            result + plang;
         }
         else if (number % 7 == 0 && i == 2)
         {
            result + plong;
         }
      }
      return result;
   }

}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Zenmoa
  • 31
  • 5

2 Answers2

3

There are 2 problems with your code, even though the compiler only shows one.

The line result+plong is the root of both problems. This is a useless line, or as the compiler says, it is not a statement. Why? You don't call any methods, you don't assign or declare any variables. Since there is a + operator it should append the strings, but then it doesn't know what to do with it - so it fails in compile-time.

The other problem is with your result variable. You never assigned it. This means that you can't use the += operator on it (as you probably intended), and cannot safely return it. To fix this issue, just use String result=""; instead of only declaring it.

Your final code:

String convert(int number) {
 String pling = "Pling";
 String plang = "Plang";
 String plong = "Plong";
 String result = "";
  for (int i = 0;i < 3;i++)
  {
     if(number % 3 == 0 && i == 0)
     {
        result += pling;
     }
     else if (number % 5 == 0 && i == 1)
     {
        result += plang;
     }
     else if (number % 7 == 0 && i == 2)
     {
        result += plong;
     }
  }
  return result;
}
1

This is an expression:

result + plang;

It is like just mentioning the combination of current result and another string, but not saying to update result.

What you obviously want is an assignment:

result = result + plang;

That way the final return result; should have the effect you intend.

Information on possible problems with the concatenation itself you can find here:
String concatenation: concat() vs "+" operator

Yunnosch
  • 26,130
  • 9
  • 42
  • 54