[英]Make the loop results appear in an array through Arrays.toString in Java
[英]I'm stuck trying to write a loop through an array for results in a toString
/**
* 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;
}
大家好,我已经坚持写这个 toString 好几天了。 有人可以帮我弄清楚如何编写一个循环来从头到尾显示数组中的所有元素。 我只是不断出现卡住。 如您所见,我已经开始编写一个循环,但现在我不知道它是否开始正确。 谢谢!
您尚未在for()
循环中将要获取的内容添加到output
String中! 您将需要将其更改为以下内容:
for (int i = 0; i < this.nextPos; ++i)
{
output += this.results[i].getRFID();
output += this.results[i].getGender();
output += "\n";
}
围绕此添加您喜欢的其他任何格式。 代码中的注释表示您将希望在整个循环中每次都添加一个类似于“啮齿动物的信息:”的字符串,以及每个字段的标题和指示符以及它们之间的换行符。
祝好运!
另外,要扩展@Matt在问题下方的注释中所说的内容,您在for()
循环中进行的比较非常奇怪,并且可能没有按照您想要的去做(尽管也许是,而且我们都只是约定的贴纸)。 通常,在遍历数组或集合时,您将与集合的长度进行比较,而不是“下一个位置”中的内容(这是我认为变量的含义)。
嗯,如果您循环执行并且经常执行,则可以考虑使用StringBuilder
。 String
在Java中是不可变的,因此,您会在该循环中随处产生一堆新字符串。 伊维金
一个简短的例子
StringBuilder output = new StringBuilder("");
for(int i = 0; i < this.nextPos; ++i) {
output.append(this.results[i].getRFID());
...
}
return output.toString();
如果要合并结果,则只需执行与在此处执行的操作类似的output += "Competition Results:" + "\\n";
。 只需在循环内做同样的事情:
for (int i = 0; i < this.nextPos; ++i)
{
output += this.results[i].getRFID().toString();
output += " "; // you may want to separate the strings
output += this.results[i].getGender().toString();
}
顺便说一下, 这种方法非常慢 ,请参阅此处有关不同字符串接触技术的比较。
一种更快的方法是使用StringBuilder :
StringBuilder sb = new StringBuilder();
for (int i = 0; i < this.nextPos; ++i)
{
sb.append(this.results[i].getRFID().toString());
sb.append(this.results[i].getGender().toString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.