[英]How to return multiple values without using Collections?
我正在使用课本Murach的java编程,在其中一个练习中,它要求我执行以下操作:
添加此方法(由本书给出):
private static String displayMultiple(Displayable d, int count)
编写此方法的代码,以便返回一个String , 该String包含Displayable参数int参数指定的次数。
Displayable
是一个实现getDisplayText()
的接口。 此方法只返回一个带有对象实例变量的String
,即对于Employee,它返回名字,姓氏,部门和工资。
一切都有效,除了“ 返回一个字符串 ”。
这可能是关于循环的练习:
d
转换为字符串: getDisplayText
。 这就产生了"ABCD"
"ABCD"
count
时间。 如果count == 3
,则表示"ABCDABCDABCD"
。 有用的关键字: for loop
, StringBuilder
。 这是一个可用于入门的模板:
String text = ;// Use getDisplayText here
StringBuilder ret = new StringBuilder();
/* Loop from 0 to count - 1 */ {
// Append `text` to `ret`
}
return ret.toString();
您实际上不需要返回多个值。
据我了解:
private static String displayMultiple(Displayable d, int count){
String s = "";
String ss = d.getDisplayText();
for(int i=0; i<count; i++){
s += ss;
}
return s;
}
如果你想使用集合返回多个值,那么你可以创建一个类 -
public class MultipleValue{
String firstValue;
String secondValue;
//other fields
}
然后从someMethod()
中你想要返回多个值(即firstValue
, secondValue
),你可以这样做 -
public MultipleValue someMethod(){
MultipleValue mulVal = new MultipleValue();
mulVal.setFirstValue("firstValue");
mulVal.setSecondValue("secondVAlue");
return mulVal;
}
然后从someMethod()
的调用类中,您可以像这样提取多个值(即firstValue
和secondValue
) -
//from some calling method
MultipleValue mulVals = someMethod();
String firstValue = mulVals.getFirstValue();
String secondValue = mulVals.getSecondValue();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.