Search code examples
javastringstack

Turn my stack into a string?


String message = ""; //a string to store the whole message
for (int c = stack.length - 1; c >= 0; c--) {
message += ", "+stack[c];  //add the next element to the message
}
message = message.substring(2); //cut off the first ", "
return message;

This worked in solving my problem; thanks


Solution

  • Calling return in a loop will immediately exit the loop. What you need to do is something like this:

    String message = ""; //a string to store the whole message
    for (int c = stack.length - 1; c >= 0; c--) {
      message += ", "+stack[c];  //add the next element to the message
    }
    message = message.substring(2); //cut off the first ", "
    return message;