Java Control Flow: Conditionals and Loops

JavaJavaBeginner
Practice Now

Introduction

In this lab, you'll dive into the world of Java control flow structures. These are essential tools that allow your programs to make decisions and repeat actions. We'll cover three main concepts:

  1. If-else statements for decision making
  2. For loops for repeating actions a known number of times
  3. While loops for repeating actions when you don't know how many times you'll need to repeat

Don't worry if these terms sound unfamiliar - we'll explain each one in detail. By the end of this lab, you'll be able to write Java programs that can make decisions and repeat actions, opening up a whole new world of possibilities in your coding journey!


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java/ObjectOrientedandAdvancedConceptsGroup -.-> java/user_input("`User Input`") java/BasicSyntaxGroup -.-> java/for_loop("`For Loop`") java/BasicSyntaxGroup -.-> java/if_else("`If...Else`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/BasicSyntaxGroup -.-> java/while_loop("`While Loop`") subgraph Lab Skills java/user_input -.-> lab-413751{{"`Java Control Flow: Conditionals and Loops`"}} java/for_loop -.-> lab-413751{{"`Java Control Flow: Conditionals and Loops`"}} java/if_else -.-> lab-413751{{"`Java Control Flow: Conditionals and Loops`"}} java/output -.-> lab-413751{{"`Java Control Flow: Conditionals and Loops`"}} java/variables -.-> lab-413751{{"`Java Control Flow: Conditionals and Loops`"}} java/while_loop -.-> lab-413751{{"`Java Control Flow: Conditionals and Loops`"}} end

Understanding If-Else Statements

Imagine you're creating a program that gives weather advice. You want it to suggest different things based on the temperature. This is where if-else statements come in handy!

  1. Open the WeatherAdvisor.java file in the WebIDE. You'll see this code:

    public class WeatherAdvisor {
        public static void main(String[] args) {
            int temperature = 28; // Temperature in Celsius
    
            System.out.println("The temperature is " + temperature + "°C.");
    
            // TODO: Add if-else statements here to provide weather advice
        }
    }

    Here's a breakdown of the code:

    1. public class WeatherAdvisor:

      • This line declares a public class named WeatherAdvisor.
      • In Java, every program must have at least one class, and the class name should match the filename (in this case, WeatherAdvisor.java).
    2. public static void main(String[] args):

      • This is the main method, which is the entry point of any Java program.
      • public: This method can be accessed from outside the class.
      • static: This method belongs to the class itself, not to any specific instance of the class.
      • void: This method doesn't return any value.
      • main: This is the name of the method. Java looks for a method named "main" to start executing the program.
      • (String[] args): This allows the method to accept command-line arguments (though we're not using them in this example).
    3. int temperature = 28;:

      • This line declares an integer variable named temperature and initializes it with the value 28.
      • int is the data type for whole numbers in Java.
      • The comment // Temperature in Celsius explains what this value represents.
    4. System.out.println("The temperature is " + temperature + "°C.");:

      • This line prints a message to the console.
      • System.out.println() is a method that outputs text and moves to a new line.
      • The + operator is used here for string concatenation, combining the text with the value of the temperature variable.
      • The °C at the end adds the Celsius symbol to the output.

    This basic structure sets up a program that defines a temperature and prints it out. It provides a foundation for adding more complex logic, such as the if-else statements we added later to give weather advice based on the temperature value.

  2. Replace the TODO comment with the following code:

    if (temperature > 30) {
        System.out.println("It's a hot day. Remember to stay hydrated!");
    } else if (temperature > 20) {
        System.out.println("It's a nice warm day. Enjoy the weather!");
    } else if (temperature > 10) {
        System.out.println("It's a bit cool. You might need a light jacket.");
    } else {
        System.out.println("It's cold. Wear warm clothes!");
    }
    alt text

    Let's break this down:

    • The if statement checks if the temperature is above 30°C.
    • If it's not, it moves to the first else if and checks if it's above 20°C.
    • This continues until it finds a condition that's true, or reaches the else at the end.
    • Only one of these blocks will run - as soon as a condition is true, Java skips all the rest.
  3. Save the file. In most IDEs, including WebIDE, you can save by pressing Ctrl+S (or Cmd+S on Mac).

  4. Now let's compile the program. In the terminal at the bottom of your WebIDE, type:

    javac ~/project/WeatherAdvisor.java

    This command tells Java to compile your code. If you see no output, that's good! It means there were no errors.

  5. To run the program, type:

    java -cp ~/project WeatherAdvisor

    The -cp ~/project part tells Java where to find your compiled code.

  6. You should see this output:

    The temperature is 28°C.
    It's a nice warm day. Enjoy the weather!

    This matches our code because 28°C is above 20°C but not above 30°C.

  7. Let's experiment! Change the temperature value in the code to 35, then save, compile, and run again. You should see:

    The temperature is 35°C.
    It's a hot day. Remember to stay hydrated!
  8. Try changing the temperature to 15 and 5, compiling and running each time. Watch how the output changes!

Congratulations! You've just written a program that makes decisions. This is a fundamental concept in programming that you'll use all the time.

Working with For Loops

Now, let's learn about for loops. These are great when you want to repeat something a specific number of times - like creating a multiplication table!

  1. Open the MultiplicationTable.java file in the WebIDE. You'll see:

    public class MultiplicationTable {
        public static void main(String[] args) {
            int number = 5;
            System.out.println("Multiplication table for " + number + ":");
    
            // TODO: Add a for loop here to print the multiplication table
        }
    }
  2. Replace the TODO comment with this for loop:

    for (int i = 1; i <= 10; i++) {
        int result = number * i;
        System.out.println(number + " x " + i + " = " + result);
    }

    Let's break this down:

    • for (int i = 1; i <= 10; i++) is the for loop statement:
      • int i = 1 creates a variable i and sets it to 1. This happens once at the start.
      • i <= 10 is the condition. The loop keeps going as long as this is true.
      • i++ increases i by 1 each time the loop finishes.
    • Inside the loop, we multiply number by i and print the result.
    • This will repeat 10 times, with i going from 1 to 10.
  3. Save the file.

  4. Compile the program:

    javac ~/project/MultiplicationTable.java
  5. Run the program:

    java -cp ~/project MultiplicationTable
  6. You should see the multiplication table for 5:

    Multiplication table for 5:
    5 x 1 = 5
    5 x 2 = 10
    5 x 3 = 15
    5 x 4 = 20
    5 x 5 = 25
    5 x 6 = 30
    5 x 7 = 35
    5 x 8 = 40
    5 x 9 = 45
    5 x 10 = 50

    See how it printed the table from 1 to 10? That's our for loop in action!

  7. Let's experiment! Change the number variable to 7, then save, compile, and run again. You should see the multiplication table for 7.

  8. Want to see more? Try changing i <= 10 to i <= 15 in the for loop. This will make the table go up to 15 instead of 10.

For loops are incredibly useful when you know exactly how many times you want to repeat something. You'll use them a lot in your programming journey!

Exploring While Loops

While loops are perfect for situations where you don't know in advance how many times you need to repeat something. Let's use one to create a number guessing game!

  1. Open the GuessTheNumber.java file in the WebIDE. You'll see:

    import java.util.Random;
    import java.util.Scanner;
    
    public class GuessTheNumber {
        public static void main(String[] args) {
            Random random = new Random();
            int numberToGuess = random.nextInt(100) + 1; // Random number between 1 and 100
            Scanner scanner = new Scanner(System.in);
            int guess;
            int attempts = 0;
    
            System.out.println("I'm thinking of a number between 1 and 100. Can you guess it?");
    
            // TODO: Add a while loop here to implement the guessing game
    
            scanner.close();
        }
    }

    This code sets up a random number for the player to guess, and a scanner to read the player's input.

  2. Replace the TODO comment with this while loop:

    while (true) {
        System.out.print("Enter your guess: ");
        guess = scanner.nextInt();
        attempts++;
    
        if (guess < numberToGuess) {
            System.out.println("Too low! Try again.");
        } else if (guess > numberToGuess) {
            System.out.println("Too high! Try again.");
        } else {
            System.out.println("Congratulations! You guessed the number in " + attempts + " attempts.");
            break;
        }
    }

    Let's break this down:

    • while (true) creates an infinite loop. It will keep going until we tell it to stop.
    • Inside the loop, we ask for a guess and increase the attempt counter.
    • We use if-else statements to check if the guess is too low, too high, or correct.
    • If the guess is correct, we print a congratulations message and use break to exit the loop.
  3. Save the file.

  4. Compile the program:

    javac ~/project/GuessTheNumber.java
  5. Run the program:

    java -cp ~/project GuessTheNumber
    alt text
  6. Now play the game! Keep entering numbers until you guess correctly. The program will tell you if you're too high or too low.

This while loop keeps going until the correct number is guessed. We don't know how many attempts it will take, which is why a while loop is perfect here.

Combining Control Structures

For our final challenge, we'll combine if-else statements, for loops, and while loops to create a prime number finder!

  1. Open the PrimeNumberFinder.java file in the WebIDE. You'll see:

    import java.util.Scanner;
    
    public class PrimeNumberFinder {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int count = 0;
            int number = 2;
    
            System.out.print("How many prime numbers do you want to find? ");
            int maxPrimes = scanner.nextInt();
    
            System.out.println("First " + maxPrimes + " prime numbers:");
    
            // TODO: Implement the prime number finding logic here
    
            scanner.close();
        }
    }
  2. Replace the TODO comment with this code:

    while (count < maxPrimes) {
        boolean isPrime = true;
    
        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0) {
                isPrime = false;
                break;
            }
        }
    
        if (isPrime) {
            System.out.print(number + " ");
            count++;
        }
    
        number++;
    }

    This looks complex, but let's break it down:

    • We use a while loop to keep finding primes until we have the desired amount.
    • For each number, we use a for loop to check if it's prime.
    • We use Math.sqrt(number) as an optimization - we only need to check up to the square root of the number.
    • If we find a divisor, we know the number isn't prime, so we set isPrime to false and break the inner loop.
    • If isPrime is still true after the for loop, we print the number and increase our count.
    • We always increase number at the end to move to the next number.
  3. Save the file.

  4. Compile the program:

    javac ~/project/PrimeNumberFinder.java
  5. Run the program:

    java -cp ~/project PrimeNumberFinder
  6. When prompted, enter a number (like 10) to find that many prime numbers. You should see output like:

    How many prime numbers do you want to find? 10
    First 10 prime numbers:
    2 3 5 7 11 13 17 19 23 29

This program showcases how powerful Java can be when you combine different control structures. You're now able to create programs that can make decisions, repeat actions, and solve complex problems!

Summary

Fantastic work! In this lab, you've mastered some of the most important concepts in Java programming:

  1. If-else statements: You used these to make decisions in your weather advisor program.
  2. For loops: You used these to create a multiplication table, repeating an action a specific number of times.
  3. While loops: You used these in your guessing game, repeating an action until a condition was met.
  4. Combining control structures: You brought it all together to create a prime number finder.

These control flow structures are the building blocks of complex programs. With them, you can create programs that make decisions, repeat actions, and solve intricate problems.

Remember, practice makes perfect. Try modifying these programs or creating new ones using these concepts. Can you make a program that gives different advice for each day of the week? Or one that prints out a times table for any number up to 100? The possibilities are endless!

Keep coding, keep learning, and most importantly, have fun! You're well on your way to becoming a Java expert.

Other Java Tutorials you may like