0

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;
        }

}
2
  • 1
    Please, Please, Please do not do this. Return an int[] or List<int>. Commented Mar 17, 2014 at 15:50
  • That loop is going to run forever if you remove the return from it, or else it's going to exit the first time through if it has the return in it. Either way, it doesn't make sense. Commented Mar 17, 2014 at 16:19

2 Answers 2

1

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();

}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

You can eliminate the trailing comma by conditionally appending it if (i > arg2+1) and you can improve things greatly by creating a StringBuilder. Otherwise, Java is going to create a new StringBuilder every time around the loop.
@DavidConrad Eliminating comma: yes, but I hoped to goad OP into working that out for himself. StringBuilder: blog.codinghorror.com/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.