PROGRAMMING

  minte9
learningjourney




S R Q

Loops

p114 Use for loop when you know how many times you want to loop.
 
/** 
 * For Loop, when you know how many loops
 * Enhanced For Loop, index not needed
 * ForEach, loop over a Collection, ofthen used with ...
 * lambdas or  method reference
 */

package com.minte9.basics.loops;
import java.util.Arrays;
import java.util.List;

public class Loops {            
    public static void main(String[] args) {
        
        for (int i=0; i<3; i++) {
            System.out.println(i); // 0 1 2
        }

        int[] nums = {10, 20, 30};
        for (int no : nums) {
            System.out.println(no); // 10 20 30
        }

        List<Integer> data = Arrays.asList(100, 200, 300);
        data.forEach(x -> System.out.println(x));  // 100 200 300
        data.forEach(System.out::println); // 100 200 300
    }
}

Break

Use labels to exit from multiple loops.
 
/**
 * Break statement, to exit from a loop
 * For multiple loops use labels 
 */

package com.minte9.basics.loops;

public class Break {            
    public static void main(String[] args) {
        
        int[][] numbers = { 
            {1,2,8}, 
            {4,5,6}, 
            {7,8,9},
        };

        A: for (int i=0; i<numbers.length; i++) {
            B: for (int j=0; j<numbers[i].length; j++) {

                System.out.print(i + ":" + j + " ");
                
                if (numbers[i][j] == 4) {
                    System.out.println("Break from B");
                    break B;
                }

                if (numbers[i][j] == 7) {
                    System.out.println("Break from A");
                    break A;
                }
                
                // 0:0 0:1 0:2 1:0 Break from B 
                // 2:0 Break from A
            }    
        }
    }
}

Questions    
Last update: 49 days ago
Numbers