Reputation: 3
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]);
}
Upvotes: 0
Views: 401
Reputation: 155
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
Upvotes: 1
Reputation: 8825
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]);
}
Upvotes: 2
Reputation: 63
Do you mean:
for (int i = 0; i < f.length; i++)
Instead of:
for (int i = 1; i < f.length; i--)
Upvotes: 0