This time I want to print an array from the end to the start.
This is what I wrote:
public class Arrays {
public static void main (String[] args){
for (int i = args.length; i >=0; i--){
System.out.print(args[i]+" ");
}
}
and this is the error message: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at Assignment02Q04.main(Assignment02Q04.java:5).
Still having a hard time to realize the Eclipse error notifactions. I'll be glad for assistance.
In java arrays start with 0. So an array of length 5 has elements with index 0 to 4
The following statement
for (int i = args.length; i >=0; i--)
loops from 5 to 0 (for an array of size 5)
Change it to
for (int i = args.length-1; i >=0; i--)
and bingo!
PS: Actually you did loop till 0, so you probably already knew that arrays start at 0.
Java uses 0 indexing for arrays, so your args.length needs to take that into account; you should start at one before:
for (int i = args.length-1; i >=0; i--){
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With