0

I am in my first class of Java programming and one of the assignments we were given was to create a value string which displays in reverse order separated by commas. I know I am probably missing something very simple, but after hours of trying I just don't know where I am going wrong?

My code works, however I keep getting this error message:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 
    at ip2_jolley.IP2_Jolley.main(IP2_Jolley.java:148) 
Three, Two, One Java Result: 1

This is the code I am using:

String[] f = {"One", "Two", "Three"};
if (f.length > 0) System.out.print (f[2]);
for (int i = 1; i < f.length; i--){
    System.out.print(", " + f[i]); 
}
2
  • It won't let me click the up arrow so I edited to thank them. Commented Apr 6, 2014 at 21:17
  • ..and at the time I wasn't allowed to comment either. Commented Apr 6, 2014 at 21:18

3 Answers 3

2

In your code, you start at 1, loop until the length of the array, but decrement i each time. That's a bit mixed up. What you want to do is start at the end of your array (so f.length - 1) and keep moving to the "left" of the array until you are at the beginning of it. So you want this:

for (int i = f.length-1; i >= 0; i--){
   System.out.print(f[i]); 
}
Sign up to request clarification or add additional context in comments.

3 Comments

It would be fine if you explain why
Yes. You deserve my +1
Thank you changing the 1 loop to a 0 fixed the missing / wrong output =)
1

You start your loop with int i = 1 and then reduce it by 1 every loop which will result in i being lower than 0.

Instead of using int i = 1, you probably want to use int i = f.length

Edit

What you wanted is probably this:

  String[] f = {"One", "Two", "Three","Four","Five"};

    //start at f.length - 1, continue until there is no item left
    for (int i = f.length-1; i >= 0; i--){

        //print current item
        System.out.print(f[i]);

        //if it is not the last item, print separator
        if(i>0){
            System.out.print(", ");
        }
    }
}

Edited with some explanation

Comments

0

Do you mean:

for (int i = 0; i < f.length; i++)

Instead of:

for (int i = 1; i < f.length; i--)

3 Comments

I did not downvote the answer, but I imagine it is because the OP specifically is trying to display the values in reverse order.
Okay I will delete my answer then.
Thank you =) adding the ++ to replace the -- was what I needed.

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.