Logout

Home Topic 4 Last Next

Looping & Branching Extras - "For the record"

This is "for the record" and a sense of completion, but also since you're likely to come across one or two of these "the rest of the story" techniques available in Java. There's one branching, and three looping "extras", with the last of those, recursion, actually being part of the HL curriculum.

Switch - an alternative for multiple branching situations

Its advantage over the traditional if/else if/else if etc. technique in a case where it can be used without breaks, where it can "jump in" at one case, and do everything else from that point on, rather than just doing what is controlled by that particular if/else.

3public class ForSwitch {
4    public static void main(String[] args) {
5        switchWithBreaks();
6        switchWithoutBreaks();
7    }
8    public static void switchWithBreaks(){
9        switch ("Wednesday") {
10           case "Monday":
11               System.out.println("Five more days");
12               break; //using breaks, works no differently than if/else if/else if/etc.
13           case "Tuesday":
14               System.out.println("Four more days.");
15               break;
16          case "Wednesday":
17               System.out.println("Three more days..");
18               break;
19           case "Thursday":
20               System.out.println("Two more days...");
21               break;
22           case "Friday":
23               System.out.println("One more day!!!");
24               break;
25           case "Saturday":
26               System.out.println("Finally, the weekend!");
27       }
28       //Sending "Wednesday" prints only:
29       //Three more days..
30   }
31   public static void switchWithoutBreaks(){
32       switch ("Wednesday") {
33           case "Monday":
34               System.out.println("Five more,"); //without breaks added functionality - see output below
35           case "Tuesday":
36               System.out.println("Four more,");
37           case "Wednesday":
38               System.out.println("Three more,");
39           case "Thursday":
40               System.out.println("Two more,");
41           case "Friday":
42               System.out.println("One more day!!!");
43           case "Saturday":
44               System.out.println("Finally, the weekend!");
45       }
46       //Sending "Wednesday" prints:
47       /*Three more, 
48         Two more, 
49         One more day!!! 
50         Finally, the weekend! 
51        */
52   }
53}


For Each - an alternative for looping through all of an array

The only advantage over a traditional for loop is it's a bit more compact to write, and a little bit more obvious that it's a situation where all the elements in an array are being worked with. Though it is limited to always working with all elements.

public class ForEach {
    public static void main(String[] args) {
        int [] arr = {243, 70, 545, 77, 988};
        for(int x : arr){ //for each looping technique loops through each of the array elements
            System.out.println(x);
        }

        System.out.println();

        for(int i = 0; i < arr.length; i++){ //achieves the same thing as above
            System.out.println(arr[i]);
        }
        for(int i = 0; i < arr.length; i+=2){ //for each can't do this; it can only loop through all elements
            System.out.println(arr[i]);
        }
    }
}

 

Recursion - a schmantzy way of achieving looping/iteration

Refer to HL Topic 5 for advantages and disadvantages, as well as appropriate times to use this technique.

public class Recursion {
    public static void main(String[] args) {
        repeatThis(10); 
        System.out.println("Landed!!");
    }

    public static void repeatThis(int x){
        System.out.println(x);
        x--; //for working toward the base case
        if(x > 0) { //the base case
            repeatThis(x); //calling **another instance** of repeatThis() 
        }
    }
}

 

Do While - an alternative to the while loop, when loop always entered at least once

Not much of an advantage over the regular while loop, unless there is lots of processing that needn't be done twice to come up with a "continue condition" for the loop, in the case that for sure you are at least going to enter the loop once.

3import java.util.Scanner;
4
5public class ForDoWhile {
6
7    static Scanner snr = new Scanner(System.in);
8
9    public static void main(String[] args) {
10       usingWhile();
11       usingDoWhile();
12   }
13
14   public static void usingWhile(){
15       System.out.println("What is the next value of xyz?");
16       double xyz = snr.nextDouble();
17       System.out.println("Is abc true in that case? true/false");
18       boolean abc = snr.nextBoolean();
19       double efg = 0;
20       if(abc){              //All of this stuff is repeated before the while loop.
21           System.out.println("Enter the efg amount");
22           efg = snr.nextDouble();
23       }else{                //But it doesn't have to be since the loop will for sure
24           efg = -10;      //be entered at least once.
25       }
26       double result = xyz * efg;
27       double overallResult = 0;
28       while(result < 0){
30           System.out.println("What is the next value of xyz?");
31           double xyz = snr.nextDouble();     //Exactly the same stuff again inside the while loop.
32           System.out.println("Is abc true in that case? true/false");
33           boolean abc = snr.nextBoolean();
34           double efg = 0;
35           if(abc){
36               System.out.println("Enter the efg amount");
37               efg = snr.nextDouble();
38           }else{
39               efg = -10;
40           }
41           double newResult = xyz * efg;
42           overallResult += newResult;
43       }
44       System.out.println("The overall result is: " + overallResult + ".");
45   }
46
47   public static void usingDoWhile(){
48       double result = 0;
49       double overallResult = 0;
50       do{          //Here there is not the doubling of all the big calculation.
51           overallResult += result;
52           System.out.println("What is the next value of xyz?");
53           double xyz = snr.nextDouble();
54           System.out.println("Is abc true in that case? true/false");
55           boolean abc = snr.nextBoolean();
56           double efg = 0;
57           if(abc){
58               System.out.println("Enter the efg amount");
59               efg = snr.nextDouble();
60           }else{
61               efg = -10;
62           }
63          double newResult = xyz * efg;
64           overallResult += newResult;
65       }while(result < 0);
66       System.out.println("The overall result is: " + overallResult + ".");
67   }
68}