Reputation: 87
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 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.
Everything works, except for the "returns a String".
Upvotes: 2
Views: 289
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
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
Reputation: 12937
This is probably an exercise about loops:
d
to a string: getDisplayText
. This yields, say, "ABCD"
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