Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return multiple values without using Collections?

I am using textbook Murach's java programming, and in one of the exercises, it is asking me to do the following:

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.

Everything works, except for the "returns a String".

like image 253
Miguel Ortiz Avatar asked May 11 '26 08:05

Miguel Ortiz


2 Answers

This is probably an exercise about loops:

  • You have a way to convert d to a string: getDisplayText. This yields, say, "ABCD"
  • You want to return count times that string "ABCD". If count == 3, that means "ABCDABCDABCD".

Useful keywords: for loop, StringBuilder. Here is a template that you can use to get started:

String text = ;// Use getDisplayText here
StringBuilder ret = new StringBuilder();
/* Loop from 0 to count - 1 */ {
    // Append `text` to `ret` 
}
return ret.toString();

You don't actually need to return multiple values.

like image 83
Clément Avatar answered May 12 '26 21:05

Clément


As I understand it:

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;
}
like image 44
Eric Leibenguth Avatar answered May 12 '26 22:05

Eric Leibenguth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!