java 如何返回多个字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15902098/
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
How to return multiple Strings?
提问by Blank1268
I am working on a program to give you a hand of cards but I'm not really sure why it's not returning the cards. This is a method from my class Builder which generates a random card:
我正在开发一个程序来给你一手牌,但我不确定为什么它不归还牌。这是我的 Builder 类中的一个方法,它生成一张随机卡片:
public static String hand(){
String card = Builder();
String card2 = Builder();
String card3 = Builder();
String card4 = Builder();
String card5 = Builder();
out.println("Your hand is: ");
out.println( card );
out.println( card2 );
out.println( card3 );
out.println( card4 );
out.println( card5 );
return card;
return card2;
return card3;
return card4;
return card5;
回答by AmitG
I would recommend you to read "Head first core java" ASAP.
You can return only one value from method. If you still want that all variable should be set to given cards then follow below approach. In such case you need not to return even single value(see return type is void
). Everything is set inside the method.
我建议你尽快阅读“ Head first core java”。
您只能从方法返回一个值。如果您仍然希望所有变量都设置为给定的卡片,请遵循以下方法。在这种情况下,您甚至不需要返回单个值(请参阅返回类型是void
)。一切都在方法中设置。
class Play {
String card;
String card2;
String card3;
String card4;
String card5;
public void hand() {
this.card = builder();
this.card2 = builder();
this.card3 = builder();
this.card4 = builder();
this.card5 = builder();
}
private static String builder() {
// return random card
return null; //temporary set to null
}
}
回答by Tanny
No you cannot return more than one value.
But you can send an array of strings containing all those strings.
不,您不能返回多个值。
但是您可以发送包含所有这些字符串的字符串数组。
To declare the method, try this:
要声明该方法,请尝试以下操作:
Public String[] hand() {
String card = Builder();
String card2 = Builder();
String card3 = Builder();
String card4 = Builder();
String card5 = Builder();
return new String[] {card, card2, card3, card4, card5};
}
回答by Blank1268
Return a String
array:
返回一个String
数组:
return new String[] {card, card2, card3, card5, card5};
Edit:
编辑:
To make this work, you must change the return type of your method to String[]
.
要使这项工作起作用,您必须将方法的返回类型更改为String[]
.
I recommend the Java Tutorial on defining methods.
回答by Robert Northard
You can only return one value, why don't you return a String array
只能返回一个值,为什么不返回一个String数组
return new String[] {card, card2, card3, card4, card5};