Java Flow Control

Previously we learned basic syntax without user interaction. Now the Scanner class lets us capture keyboard input and process it—enabling real interactive programs.

Basic Syntax

Scanner inputReader = new Scanner(System.in);

We use next() and nextLine() to read strings. Before reading, we can check for data with hasNext() or hasNextLine().

Example using next():

package com.flow.scanner;

import java.util.Scanner;

public class NextMethodDemo {
    public static void main(String[] args) {
        // Create a scanner to receive keyboard input
        Scanner inputReader = new Scanner(System.in);
        System.out.println("Using next() method:");

        // Check if user entered a string (optional)
        if (inputReader.hasNext()) {
            String userText = inputReader.next(); // waits for input
            System.out.println("Output: " + userText);
        }
        // Close scanner to free resources
        inputReader.close();
    }
}

Example using nextLine():

package com.flow.scanner;

import java.util.Scanner;

public class NextLineDemo {
    public static void main(String[] args) {
        Scanner inputReader = new Scanner(System.in);
        System.out.println("Using nextLine() method:");
        if (inputReader.hasNextLine()) {
            String userText = inputReader.nextLine();
            System.out.println("Output: " + userText);
        }
        inputReader.close();
    }
}

If you type "hello world", next() only returns "hello", while nextLine() returns the full "hello world".

Differences:

next():

  1. Only stops input after reading valid characters.
  2. Cannot read strings containing spaces.
  3. Space is treated as a delimiter.

nextLine():

  1. Stops at the Enter key.
  2. Can read spaces.

Advanced Usage – Typed Input

package com.flow.scanner;

import java.util.Scanner;

public class TypeCheckDemo {
    public static void main(String[] args) {
        Scanner inputReader = new Scanner(System.in);
        int intValue = 0;
        float floatValue = 0.0f;

        System.out.println("Enter an integer:");
        if (inputReader.hasNextInt()) {
            intValue = inputReader.nextInt();
            System.out.println("Integer: " + intValue);
        } else {
            System.out.println("Not an integer!");
        }

        System.out.println("Enter a decimal:");
        if (inputReader.hasNextFloat()) {
            floatValue = inputReader.nextFloat();
            System.out.println("Decimal: " + floatValue);
        } else {
            System.out.println("Not a decimal!");
        }

        inputReader.close();
    }
}

Read multiple numbers, calculate sum and average:

package com.flow.scanner;

import java.util.Scanner;

public class SumAndAverage {
    public static void main(String[] args) {
        Scanner inputReader = new Scanner(System.in);

        double total = 0;
        int count = 0;

        // Loop while numbers are entered; non-number input ends the loop
        while (inputReader.hasNextDouble()) {
            double value = inputReader.nextDouble();
            count++;
            total += value;
            System.out.println("You entered the " + count + "th number, current total = " + total);
        }
        System.out.println("Sum of " + count + " numbers: " + total);
        System.out.println("Average: " + (total / count));

        inputReader.close();
    }
}

Sequential Structure

Execution proceeds line by line, top to bottom. This is the fundamental structure of any algorithm.

Selection Structures

  1. if (single)
  2. if-else (double)
  3. if-else if-else (multiple)
  4. Nested if
  5. switch

Single if

package com.flow.branch;

import java.util.Scanner;

public class IfSingle {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        System.out.println("Enter text:");
        String input = reader.nextLine();
        if (input.equals("Hello")) {
            System.out.println(input);
        }
        System.out.println("End");
        reader.close();
    }
}

if-else

package com.flow.branch;

import java.util.Scanner;

public class IfDouble {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        System.out.println("Enter score:");
        int score = reader.nextInt();
        if (score >= 60) {
            System.out.println("Pass");
        } else {
            System.out.println("Fail");
        }
        reader.close();
    }
}

if-else if-else

package com.flow.branch;

import java.util.Scanner;

public class IfMultiple {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        System.out.println("Enter score:");
        int score = reader.nextInt();

        if (score == 100) {
            System.out.println("Perfect score");
        } else if (score >= 90) {
            System.out.println("A");
        } else if (score >= 80) {
            System.out.println("B");
        } else if (score >= 70) {
            System.out.println("C");
        } else if (score >= 60) {
            System.out.println("D");
        } else if (score >= 0) {
            System.out.println("Fail");
        } else {
            System.out.println("Invalid score");
        }
        reader.close();
    }
}

Note:

  1. At most one else, and it must be after all else if.
  2. Multiple else if blocks are allowed, before the final else.
  3. Once an else if condition is true, the remaining blocks are skipped.

Nested if

(Same logic as above, placed inside another if block.)

switch

package com.flow.branch;

public class SwitchGrade {
    public static void main(String[] args) {
        char grade = 'C';  // test value

        switch (grade) {
            case 'A':
                System.out.println("Excellent");
                break;
            case 'B':
                System.out.println("Good");
                break;
            case 'C':
                System.out.println("Pass");
                break;
            case 'D':
                System.out.println("Fail");
                break;
            default:
                System.out.println("Unknown");
        }
    }
}

Switch also supports String values. (Internally characters map to numbers; after decompilation, string matching is possible.)

Loop Structures

  1. while loop
  2. do...while loop
  3. for loop

while loop

Always include a termination condition.

package com.flow.loop;

public class WhilePrint {
    public static void main(String[] args) {
        int counter = 0;
        while (counter < 100) {
            counter++;
            System.out.println(counter);
        }
    }
}

package com.flow.loop;

public class WhileSum {
    public static void main(String[] args) {
        int counter = 0;
        int total = 0;
        while (counter <= 100) {
            total += counter;
            counter++;
        }
        System.out.println(total);
    }
}

do...while loop

The body executes at least once even if the condition is false initially.

package com.flow.loop;

public class DoWhileSum {
    public static void main(String[] args) {
        int counter = 0;
        int total = 0;
        do {
            total += counter;
            counter++;
        } while (counter <= 100);
        System.out.println(total);
    }
}

for loop

The most flexible and common used loop.

package com.flow.loop;

public class ForPrint {
    public static void main(String[] args) {
        for (int idx = 1; idx <= 100; idx++) {
            System.out.println(idx);
        }
    }
}

Type 100.for in an IDE to auto-generate a for loop template:

for (int i = 0; i < 100; i++) { }

Enhanced for loop

package com.flow.loop;

public class EnhancedForDemo {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};  // define an array

        // traditional for
        for (int i = 0; i < 5; i++) {
            System.out.println(numbers[i]);
        }

        // enhanced for
        for (int num : numbers) {
            System.out.println(num);
        }
        // same output, a simplified way to iterate over arrays or collections
    }
}

Exercise 1: Sum of odd and even numbers between 0 and 100

package com.flow.exercise;

public class EvenOddSum {
    public static void main(String[] args) {
        int oddSum = 0;
        int evenSum = 0;
        for (int i = 0; i <= 100; i++) {
            if (i % 2 != 0) {
                oddSum += i;
            } else {
                evenSum += i;
            }
        }
        System.out.println("Odd sum: " + oddSum + ", Even sum: " + evenSum);
    }
}

Exercise 2: Output numbers divisible by 5 from 1 to 1000, three per line

package com.flow.exercise;

public class DivisibleByFive {
    public static void main(String[] args) {
        for (int i = 1; i <= 1000; i++) {
            if (i % 5 == 0) {
                System.out.print(i + "\t");
            }
            if (i % (5 * 3) == 0) {
                System.out.println(); // new line after every three numbers
            }
        }
    }
}

Exercise 3: Multiplication table (9×9)

package com.flow.exercise;

/*
Desired output:
1*1=1
2*1=2   2*2=4
3*1=3   3*2=6   3*3=9
...
9*1=9   9*2=18  9*3=27  9*4=36  9*5=45  9*6=54  9*7=63  9*8=72  9*9=81
*/
public class MultiplicationTable {
    public static void main(String[] args) {
        for (int row = 1; row <= 9; row++) {
            for (int col = 1; col <= row; col++) {
                // use print to stay on same line
                System.out.print(row + "*" + col + "=" + (row * col) + "\t");
            }
            System.out.println(); // move to next line after each row
        }
    }
}

break, continue, goto

Difference between break and continue

package com.flow.jump;

public class BreakContinueDemo {
    public static void main(String[] args) {
        int idx = 0;
        while (idx < 100) {
            idx++;
            System.out.println(idx);
            if (idx % 10 == 0) {
                break; // exits the loop completely
            }
        }
        System.out.println("Loop ended"); // this will execute

        int cnt = 0;
        while (cnt < 100) {
            cnt++;
            if (cnt % 10 == 0) {
                System.out.println();
                continue; // skips the rest of this iteration
            }
            System.out.print(cnt);
        }
    }
}

Summary:

break: immediately terminates the loop.

continue: skips the remaining statements in the current iteration and proceeds with the next loop cycle.

goto: not used in Java; only a reserved word.

Exercise: Print a triagnle pattern

package com.flow.exercise;

/*
     *      (1)
    ***     (3)
   *****    (5)
  *******   (7)
 *********  (9)
*/
public class TrianglePattern {
    public static void main(String[] args) {
        int rows = 5;
        for (int i = 1; i <= rows; i++) {
            // spaces decreasing
            for (int j = rows; j >= i; j--) {
                System.out.print(" ");
            }
            // left half
            for (int j = 1; j <= i; j++) {
                System.out.print("*");
            }
            // right half
            for (int j = 1; j < i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

Use the debugger (the bug icon) to step through and understand each step.

Tags: java Scanner Control Flow Branching loops

Posted on Wed, 12 Aug 2026 16:29:21 +0000 by owner