Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Java Control Flow Statements - Conditional Logic and Loop Structures

Tech May 17 2

Working with Scanner Class

To locate the Scanner class in API documentation:

  1. Type "Scanner" in the search bar
  2. The dictionary will display various input methods: nextInt(), nextDouble(), nextFloat(), nextLong(), nextByte(), nextShort(), next(), and others.
// Example of using Scanner methods to retrieve different data types
// Import statement: import java.util.Scanner;
import java.util.Scanner;

class InputReader {
    public static void main(String[] args) {
        // Instantiate Scanner object
        InputReader reader = new InputReader();
        Scanner input = new Scanner(System.in);
        
        // Using Scanner methods to capture user input
        System.out.print("Enter your name: ");
        String userName = input.next(); // String input
        System.out.println(userName);
        
        System.out.print("Enter your age: ");
        int userAge = input.nextInt();
        System.out.println(userAge);
        
        System.out.print("Enter your weight: ");
        double bodyWeight = input.nextDouble();
        System.out.println(bodyWeight);
        
        System.out.print("Do you like me? (true/false): ");
        boolean affection = input.nextBoolean();
        System.out.println(affection);

        // For character input, Scanner lacks direct methods. Use string and extract character
        System.out.print("Enter your gender (M/F): ");
        String genderInput = input.next(); // "M"
        char genderChar = genderInput.charAt(0); // Reference API: String class, find char method, index at 0
    }
}

Conditional Branching Examples

Key considerations:

  • Match input type with corresponding method - mismatch causes errors
  • else blocks are optional
  • Percision in condition defniitions is crucial
import java.util.Scanner;
class GradeEvaluator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter student's exam score (0-100): ");
        int grade = scanner.nextInt();
        
        if (grade == 100) {
            System.out.println("Reward: BMW car");
        } else if (grade > 80 && grade <= 99) {
            System.out.println("Reward: iPhone Xs Max");
        } else if (grade >= 60 && grade <= 80) {
            System.out.println("Reward: iPad tablet");
        } else {
            System.out.println("No reward this time");
        }
    }
}

Sorting Three Numbers

This example demonstrates sorting three integers using conditional statements:

import java.util.Scanner;
class NumberSorter {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        System.out.print("Enter first number: ");
        int firstNum = input.nextInt();
        System.out.print("Enter second number: ");
        int secondNum = input.nextInt();
        System.out.print("Enter third number: ");
        int thirdNum = input.nextInt();
        
        if (firstNum >= secondNum) {
            if (thirdNum >= firstNum) {
                System.out.println(secondNum + ", " + firstNum + ", " + thirdNum);
            } else if (thirdNum <= secondNum) {
                System.out.println(thirdNum + ", " + secondNum + ", " + firstNum);
            } else {
                System.out.println(secondNum + ", " + thirdNum + ", " + firstNum);
            }
        } else {
            if (thirdNum >= secondNum) {
                System.out.println(firstNum + ", " + secondNum + ", " + thirdNum);
            } else if (thirdNum <= firstNum) {
                System.out.println(thirdNum + ", " + firstNum + ", " + secondNum);
            } else {
                System.out.println(firstNum + ", " + thirdNum + ", " + secondNum);
            }
        }
    }
}

Dog Age Calculator

Converts dog years to human equivalent:

class DogAgeConverter {
    public static void main(String[] args) {
        int dogYears = 6;
        if (dogYears >= 0 && dogYears <= 2) {
            System.out.println("Human equivalent: " + dogYears * 10.5);
        } else if (dogYears > 2) {
            System.out.println("Human equivalent: " + (2 * 10.5 + (dogYears - 2) * 4));
        } else {
            System.out.println("Invalid age: dog not born yet");
        }
    }
}

Generating Random Numbers

Using Math.random() with type casting:

int randomValue = (int)(Math.random() * 90 + 10); // Range [10, 99]
// General formula: [a, b] range: (int)(Math.random() * (b - a + 1) + a)

Switch-Case Structure

Syntax pattern:

switch (expression) {
    case constant1:
        statement1;
        // break;
    case constant2:
        statement2;
        // break;
    default:
        statementN;
        // break;
}

Important rules for switch-case:

  • Expression supports: byte, short, char, int, Enum (JDK 5.0+), String (JDK 7.0+)
  • Identical cases can be merged
  • break statements are optional
  • Can incorporate if-else within switch blocks

Loop Structures

For loop components:

  • Initialization: i = 0
  • Condition: i <= 10
  • Body: execution code
  • Increment: i++
// Basic for loop syntax: for(initialization; condition; increment) { body }

// Example 1: Repetitive output
for(int counter = 0; counter <= 10; counter++) {
    System.out.println("Practice makes perfect through consistent coding");
}

// Example 2: Sequential number printing
for(int num = 1; num <= 100; num++) {
    System.out.println(num);
}

// Example 3: Combining loops with conditions
int sumOdd = 0;
for (int index = 1; index <= 100; index++) {
    if(index % 2 != 0) {
        System.out.println("Odd numbers 1-100: " + index);
        sumOdd += index;
    }
}
System.out.println("Sum of odd numbers 1-100: " + sumOdd);

Tags: Java

Related Articles

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.