簡體   English   中英

我被困在嘗試通過數組編寫循環以獲取 toString 的結果

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM