Any problem with this Java

Hello @Alpha2020,
It seems that your code returns a value in case the user has input m , cm, km for the FormatUnit and ToUnit .But what in the case the user has input something different, your code will not return anything. So you would probably get an error missing return statement,etc.. You can either try to add a return statement before the end of your method that returns an empty string, your code shouldn't get there except if the user has input a value which your if-then didn't use , or it would have break on a previousreturn statement, here is an example:

public String Test(String str) {
  if (str == "test") {
    return "it's test";
  } else if (str == "production") {
    return "we are in production";
  }
  return "unknown value"; // if we got here do the value is neither equal to test nor equal to production.
}

You could also add an else condition for all of the if-then statements.But it wouldn't be a good solution, as it would unnessecceraly make your code massive.
Lastly, you could use a local result variable initialized to "unknown value", and instead of returning just assign the result to this variable and return it at the end of your method, in case value has been assigned to it, it will remain "unknown value", example:

public String Test(String str) {
  String result = "unknown value";
  if (str == "cm") {
    result = "that's cm";
  } else if (str == "km") {
    result = "that's km";
  }
  return result;
}

Another possible error would be that you're returning an int,while you've defined the return type to String, you should change it into int.

Also as the log says your outer public class should be with the same name as your filename (in appybuilder case it would be the project name)
Also, using many if-then code isn't always useful,try to use if then return statement instead, example:

if ( FromUnit == "String") {
  return ToUnit == "cm" ? "Some value" : (ToUnit == "m" ? "Some other value" : (ToUnit == "km" ? "Some new value" : "unknown input"));
}

Note: please follow the naming conventions in your blocks, and class name, see also here:

Note2: It's java and not java script :sweat_smile: I've changed your title accordingly.

5 Likes