简体   繁体   中英

Printing multiple strings from an array as a single string

I want to print multiple Strings from an Array utilizing a for-loop, it will print a full first and last name, but only once. Here's my method for doing this.

This is the output I get:

"firstName secondName, "

There should be mutliple full names being printed.

The problem here is that in each iteration, you create a new memory location for list and so every time the loop executes, the value of list is overwritten . You can fix this by appending to list instead of changing the value of list in every iteration.

A side note, since Strings are immutable in java, for every iteration of the for loop, new memory will be allocated for list . This is not very efficient. You should instead use StringBuilder which is mutable. It would look like this.

StringBuilder str = new StringBuilder(list);

Then you can append to str :

str.append("any string");

This is equivalent to str + "any string"

Using StringBuilder, memory will be allocated to str only once and all the changes will take in place which is much more efficient. And finally you want to return a String object so you can call the method toString() on the StringBuilder object to convert it back into a String.

So, finally it would look like this :

public String getTANames() {
StringBuilder str = new StringBuilder("");
for(int i = 0; i < TAList.length; i++){
    str.append(TAList[i].first + " " + TAList[i].second + ", ");         
}
return str.toString();

}

You are very close. The problem is you keep resetting list every time you iterate over TANames . Try this instead:

public String getTANames() {
    String list = "";
    for(int i = 0; i < TAList.length; i++){
        list += TAList[i].first + " " + TAList[i].second + ", ";
    }
    return list;
}

The difference is this line here: list += TAList[i].first + " " + TAList[i].second + ", "; you are adding to list not setting list .

In your current code, every loop changes the value of the list variable. To fix the issue, replace the current = with the += as follows:

list += TAList[i].first + " " + TAList[i].second + ", ";

public String getTANames() {
    String list = "";
    for(int i = 0; i < TAList.length; i++){
        list += TAList[i].first + " " + TAList[i].second + ", ";
    }
    return list;
}

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM