Commit 85e71ceb authored by Trisha Gee's avatar Trisha Gee
Browse files

Failing for loop examples but with List

parent 47466fbd
Loading
Loading
Loading
Loading
+23 −22
Changes for src/main/java/Ch10c.java: 23 added lines, 22 removed lines.
Original line number Diff line number Diff line
@@ -21,51 +21,52 @@ public class Ch10c {

    // 2, 3, 4, 5
    static void badFor1() {
        int[] ints = {1, 2, 3, 4, 5};
        for (int i = 1; i < ints.length; i++) {
            System.out.println(ints[i]);
        List<Integer> nums = List.of(1, 2, 3, 4, 5);
        for (int i = 1; i < nums.size(); i++) {
            System.out.println(nums.get(i));
        }
    }

    //Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
    //	at Ch10c.badFor2(Ch10c.java:31)
    //	at Ch10c.main(Ch10c.java:18)
    static void badFor2() {
        int[] ints = {1, 2, 3, 4, 5};
        for (int i = 0; i <= ints.length; i++) {
            System.out.println(ints[i]);
        List<Integer> nums = List.of(1, 2, 3, 4, 5);
        for (int i = 0; i <= nums.size(); i++) {
            System.out.println(nums.get(i));
        }
    }

    // Doesn't compile
    static void badFor3() {
//        int[] ints = {1, 2, 3, 4, 5};
//        for (int i = 0; i < ints.size(); i++) {
//            System.out.println(ints[i]);
//        List<Integer> nums = List.of(1, 2, 3, 4, 5);
//        for (int i = 0; i <= nums.length; i++) {
//            System.out.println(nums.get(i));
//        }
    }

    // [I@c818063, [I@c818063, [I@c818063, [I@c818063, [I@c818063
    // [1, 2, 3, 4, 5]
    //[1, 2, 3, 4, 5]
    //[1, 2, 3, 4, 5]
    //[1, 2, 3, 4, 5]
    //[1, 2, 3, 4, 5]
    static void badFor4() {
        int[] ints = {1, 2, 3, 4, 5};
        for (int anInt : ints) {
            System.out.println(ints);
        List<Integer> nums = List.of(1, 2, 3, 4, 5);
        for (Integer num : nums) {
            System.out.println(nums);
        }
    }

    // doesn't compile
    static void badFor5() {
//        int[] ints = {1, 2, 3, 4, 5};
//        for (int int : ints) {
//            System.out.println(ints);
//        List<Integer> nums = List.of(1, 2, 3, 4, 5);
//        for (Integer int : nums) {
//            System.out.println(nums);
//        }
    }

    static void badFor6() {
        int[] ints = {1, 2, 3, 4, 5};
        Arrays.stream(ints).forEach(value -> System.out.println(value));
    static void forEach() {
        List<Integer> nums = List.of(1, 2, 3, 4, 5);
        nums.forEach(num -> System.out.println(num));
    }



}