How to return two strings in one return statement?
public String[] decode(String message)
{
String ans1 = "hey";开发者_JS百科
String ans2 = "hi";
return {ans1 , ans2}; // Is it correct?
}
This above example does not work properly. I am getting a error.
How can I achieve the initial question?
The correct syntax would be
return new String[]{ ans1, ans2 };
Even though you've created two String
s (ans1
and ans2
) you haven't created the String
array (or String[]
) you're trying to return. The syntax shown above is shorthand for the slightly more verbose yet equivalent code:
String[] arr = new String[2];
arr[0] = ans1;
arr[1] = ans2;
return arr;
where we create a length 2 String array, assign the first value to ans1
and the second to ans2
and then return that array.
return new String[] { ans1, ans2 };
The reason you have to do do this is just saying { ans1, ans2} doesn't actually create the object you are trying to return. All it does is add two elements to an array, but without "new String[]" you haven't actually created an array to add the elements to.
return new String[] {ans1 , ans2};
return new String[]{ans1,ans2};
This should work. To your other question in the comments. Since Java is strongly typed language, all the variables/results should be instantiated. Since you are not instantiating the result you want to return anywhere, we are doing the instantiation in the return statement itself.
I'm only a high school student at the moment, but an easy solution that I got from a friend of mine should work. It goes like this (this is part of a project in my AP class):
public String firstMiddleLast()
{
//returns first, middle, and last names
return (first + " " + middle + " " + last);
}
精彩评论