Java 如何在一个 return 语句中返回两个字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2301165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:51:31  来源:igfitidea点击:

How to return two strings in one return statement?

java

提问by higherDefender

public String[] decode(String message)
{
     String ans1 = "hey"; 
     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?

我怎样才能达到最初的问题?

采纳答案by Mark Elliot

The correct syntax would be

正确的语法是

 return new String[]{ ans1, ans2 };

Even though you've created two Strings (ans1and ans2) you haven't created the Stringarray (or String[]) you're trying to return. The syntax shown above is shorthand for the slightly more verbose yet equivalent code:

即使你已经创建了两个Strings ( ans1and ans2) 你还没有创建你想要返回的String数组 (or String[])。上面显示的语法是稍微冗长但等效的代码的简写:

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 ans1and the second to ans2and then return that array.

其中我们创建了一个长度为2字符串数组,分配第一值ans1和所述第二对ans2,然后返回该数组。

回答by Corey Sunwold

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.

您必须这样做的原因只是说 { ans1, ans2} 实际上并没有创建您要返回的对象。它所做的只是将两个元素添加到一个数组中,但是如果没有“new String[]”,您实际上还没有创建一个数组来添加元素。

回答by Kai Chan

return new String[] {ans1 , ans2};

回答by Saeros

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.

这应该有效。对于您在评论中的其他问题。由于 Java 是强类型语言,所有变量/结果都应该被实例化。由于您没有在任何地方实例化想要返回的结果,因此我们在 return 语句本身中进行实例化。

回答by Brian

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):

我目前只是一名高中生,但我从我的朋友那里得到的一个简单的解决方案应该可行。它是这样的(这是我 AP 课程中一个项目的一部分):

public String firstMiddleLast()
{
   //returns first, middle, and last names
    return (first + " " + middle + " " + last);
}