简体   繁体   中英

Java - Returning multiple values from loop, as single string

I have a method where I pass two int arguments, and returns a string. A loop will make sure that if the first argument(the greater value) is greater than the second, that the first will decrement until it is equal the value of the second argument(the lesser value).
The problem I'm having is that I am trying to return the value of the decremented value after each time that the loop runs. I would like to return the values as a string like "8,6,4,2".How would i set that up?

 public String countDown(int arg1, int arg2){
    if (arg1>arg2){
        for (int i = arg1; arg1>arg2;i--){
            //???

            return i;
        }

}

Use a StringBuilder:

public String countDown(int arg1, int arg2){
    final StringBuilder stringBuilder = new StringBuilder();
    if (arg1>arg2){
        for (int i = arg1; arg1>arg2;i--){
            //???
            stringBuilder.append(/*whatever*/);
        }
    }
    return stringBuilder.toString();

}

You need to put your return outside the loop.

And you need to declare an object before the loop, in which store the values as you encounter them, before finally returning it at the end.

 String out = "";
 for(int i = arg1; i>arg2; i--) {
     out = out + i + ",";
 }
 return out;

This has a couple of issues:

  • There is always an extra "," at the end of the returned String
  • Although it might be a good enough solution to your homework problem, returning a String from a method like this isn't usually the best design. It would be better to return, for example, a List of integers, because that's a structure that retains the actual "meaning" of the data more than a String does in this case.

You can find help with both of those by searching on this site (there is no need to ask another question) - or by reading ahead in your Java textbook.

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