Reputation: 7
/**
* get a formatted string with information about a competition.
*
* @return String String with information about a competition.
*
* The output should be in the following format:
* <pre>
* Rodent's Information:
* Rat RFID 787878787
* Gender: F
* Vaccination status: false
*
* Maze Information:
* Start Time: 00:00:00
* End Time: 01:00:05
* Actual Time: 01:00:05
* Contest Time: 00:59:30
* </pre>
*
*/
public String toString()
{
// your code here, replace the "X" and -9 with appropriate
// references to instance variables or calls to methods
String output = "Competition Description: " + this.desc
+ "\nCompetition Count: " + this.count + "\n";
output += "Competition Results:" + "\n";
// loop through the array from beginning to end of populated elements
for (int i = 0; i < this.nextPos; ++i)
{
this.results[i].getRFID();
this.results[i].getGender();
// get toString() for each result
return output;
}
Hi everyone, I've been stuck on writing this toString for a couple of days now. Can someone please help me figure out how to write a loop for showing all the elements in the array from beginning to end. I just keep coming up stuck. As you can see, I have started writing a loop but now I have no clue if it is started out right. Thanks!
Upvotes: 0
Views: 119
Reputation: 9260
Hm, if you do it in a loop and you do it often, you might consider StringBuilder
.
String
s are immutable in Java, you'll just get a bunch of new strings spawning everywhere in that loop, because of it. IYKWIM
A short example
StringBuilder output = new StringBuilder("");
for(int i = 0; i < this.nextPos; ++i) {
output.append(this.results[i].getRFID());
...
}
return output.toString();
Upvotes: 1
Reputation: 11572
You haven't added what you're getting to the output
String in your for()
loop! You will need to change it to something like:
for (int i = 0; i < this.nextPos; ++i)
{
output += this.results[i].getRFID();
output += this.results[i].getGender();
output += "\n";
}
Add any other formatting you like around this. The comments in your code indicate that you'll want to add a String like "Rodent's Information:" each time through the loop, as well as titles and indicators for each of the fields and line breaks in between them.
Good luck!
Also, to expand upon what @Matt said in the comments below your question, your comparison in your for()
loop is very odd and likely isn't doing what you want it to (although maybe it is, and we're all just sticklers for convention). Normally, when looping through an array or collection, you will compare to the collection's length rather than something in the "next position" (which is what I assume the meaning of your variable is).
Upvotes: 2