Object-Oriented Programming with Java, part I – Exercise 19

This program checks whether a users inputted age is between -1 and 121 and output “OK” if so and “Impossible!” if not.

My Code

import java.util.Scanner;

public class AgeCheck {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        System.out.print("How old are you? ");           //user inputs age
        int age = Integer.parseInt(reader.nextLine());
        
        if (age > (-1) && age < 121){
            System.out.println("OK");
        } else {
            System.out.println("Impossible!");
        }

    }
}

Model Code

import java.util.Scanner;

 

public class AgeCheck {

 

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

 

        System.out.print("How old are you?");

        int age = Integer.parseInt(reader.nextLine());

        if (age >= 0 && age <= 120) {

            System.out.println("OK");

        } else {

            System.out.println("Impossible!");

        }

    }

}

Comments

I failed to use the >= sign in my code which meant that I had to bracket the -1 value (Otherwise it throws an error).

Leave a comment