+ 2

Java - "Enhanced for loop" not showing first item

(not english native, sorry) I am learning enhanced for loop in Java and tried this: public class Testing{ public static void main (String[] args){ int[] numbers = {1, 2, 3, 4, 5, 6, 7}; String[] names = {"Alcine", "Beth", "Carl", "Danny", "Ermec", "Fabian", "Gutto"}; for(int x: numbers){ System.out.println("Num." + numbers[x] + ": " + names[x]); } } } ...and the output shows all numbers and names except for the first one on list and shows this error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 at Testing.main(Testing.java:11) I dont know if i did something wrong. Any clue? thanks

28th Mar 2018, 8:01 PM
srSmith
srSmith - avatar
1 Odpowiedź
+ 3
Array indexes start at 0, your numbers array starts from 1 just take away 1 from x: names[x - 1] But in this case I would just use a normal for loop, would save space by not storing the numbers array for (int i = 0; i < names.length; i++) { System.out.printf("Number %d: %s\n", i + 1, names[i]); }
28th Mar 2018, 8:19 PM
TurtleShell
TurtleShell - avatar