我正在使用 Murach 的 java 编程教科书,在其中一个练习中,它要求我执行以下操作:
add this method (given by the book):
private static String displayMultiple(Displayable d, int count)
write the code for this method so it returns a String that contains the Displayable parameter the number of times specified by the int parameter.
Displayable
is an interface that implementsgetDisplayText()
. And this method just returns aString
with instance variables of an object, i.e. for an Employee, it returns first name, last name, department, and salary.
一切正常,除了“返回字符串”。
最佳答案
这可能是一个关于循环的练习:
- 您有办法将
d
转换为字符串:getDisplayText
。比如说,这会产生"ABCD"
- 您想要返回字符串
"ABCD"
的count
次。如果count == 3
,则表示“ABCDABCDABCD”
。
有用的关键字:for循环
,StringBuilder
。您可以使用以下模板来开始使用:
String text = ;// Use getDisplayText here
StringBuilder ret = new StringBuilder();
/* Loop from 0 to count - 1 */ {
// Append `text` to `ret`
}
return ret.toString();
您实际上不需要返回多个值。
关于java - 如何在不使用集合的情况下返回多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30385212/