java - 如何在不使用集合的情况下返回多个值?

标签 java string methods collections return

我正在使用 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 implements getDisplayText(). And this method just returns a String 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/

相关文章:

string - 如何查找字符串中的单词位置(而不是字符位置)

regex - 在 Bash 中使用 2 个不同的分隔符拆分字符串

java - 为什么我不能在接口(interface)中声明静态方法?

Java JFreeChart 类别步骤图表水平(图像解释)

c - 如何将动态分配的字符串添加到 C 中的字符串数组中?

java - 类型 "YEAR"的 MySQL 到 Hibernate 数据类型映射

javascript 'this' 链接代码

java - 找不到一种方法让我的计算方法输出一个值而不是 100

java - FileChannel 映射 - 无法扩展写入

java - cplex java,未找到解决方案;如何使用exportModel()改进程序