...

/

How to Input Boolean Values

How to Input Boolean Values

Learn how to use boolean variables in the code.

We'll cover the following...

Weather clothing guide

Let’s modify the age check program example to add complexity to it so we can get an idea of how complicated this combination might become.

Note: Use true or false when prompted; otherwise, an exception will be thrown.

import java.util.Scanner; 

//MoreIfAndElse
class Main{
    static boolean isCold = false; 
    static boolean isRaining = false; 
    static boolean isTakingCar = false;

    public static void main(String[] args) {
        System.out.println("When asked, enter only true or false."); 
        System.out.println("Is it cold outside?");
        Scanner cold = new Scanner(System.in);
        isCold = cold.nextBoolean();
        System.out.println("Is it raining?"); 
        Scanner raining = new Scanner(System.in); 
        isRaining = raining.nextBoolean(); 
        System.out.println("Are you taking a car?"); 
        Scanner takingCar = new Scanner(System.in); 
        isTakingCar = takingCar.nextBoolean();

        if((isCold == true && isRaining == true) && isTakingCar == false){ 
            System.out.println("I’ll wear a windbreaker jacket with a hood.");
        } else if((isCold == true && isRaining == false) && isTakingCar == true){ 
            System.out.println("I’ll wear a windbreaker jacket without a hood.");
        } else {
            System.out.println("I won't wear a windbreaker of any kind!");
        }
    } 
}
Weather clothing guide

Let’s try the code above with different combinations of true and false to see how our code responds.

  • Output 1:
    When asked, enter only true or false.
    Is it cold outside?
    true
    Is it raining?
    true
    Are you taking a car?
    false
    I’ll wear a windbreaker
...