Miguel Ortiz
Miguel Ortiz

Reputation: 87

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".

Upvotes: 2

Views: 289

Answers (3)

Razib
Razib

Reputation: 11173

If you want to return multiple values with out using collection then you can create an Class -

public class MultipleValue{

   String firstValue;
   String secondValue;

   //other fields

}  

Then from someMethod() where you want to return multiple value (that is firstValue, secondValue) you can do this -

public MultipleValue someMethod(){

   MultipleValue mulVal = new MultipleValue();
   mulVal.setFirstValue("firstValue");
   mulVal.setSecondValue("secondVAlue");

   return mulVal;
}  

Then from the calling class of someMethod() you can extract multiple values (that is firstValue and secondValue) like this -

//from some calling method
MultipleValue mulVals = someMethod();

String firstValue = mulVals.getFirstValue();
String secondValue = mulVals.getSecondValue();

Upvotes: 2

Eric Leibenguth
Eric Leibenguth

Reputation: 4277

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;
}

Upvotes: 3

Cl&#233;ment
Cl&#233;ment

Reputation: 12937

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.

Upvotes: 6

Related Questions