Java If-else - Solution


Problem Overview

Original Problem: Java If-else | Hackerrank

Difficulty: Easy

Category: Conditionals / Decision Structures

Description: This beginner-level Java exercise introduces if else statements as a means to control program flow. You are given an integer input and asked to determine if the number is weird or not weird based on a set of conditions.

Understanding the Problem

The problem is asking us to evaluate a number to determine whether it is “Weird” or “Not Weird” based on the following criteria:

  • Odd numbers are weird

  • Even numbers from 2 to 5 (inclusive), and greater than 20, are not weird

  • Even numbers from 6 to 20 (inclusive) are weird

Input:

A single integer in the range of 1 to 100 (inclusive).

Output:

A single line of text: either “Weird” or “Not Weird”.

Initial Reasoning

This is a basic decision structure problem where we need to:

  • Use if and else statements to control program flow

  • Determine if the input number is even or odd

  • Determine what range the number is in

  • Print “Weird” or “Not Weird”

Pseudocode

// Main function:
Read the input number
If the number is odd  
    Then print "Weird"
Else 
	If the number is in the range 2–5  
		Then print "Not Weird"
	Else if the number is in the range 6–20  
		Then print "Weird"
	Else if the number is greater than 20  
		Then print "Not Weird"

Solution Code

// Note this is one of many possible solutions
import java.util.Scanner;

public class Solution {
  
    public static void main(String[] args) {
        // Create Scanner object to read input 
        Scanner scanner = new Scanner(System.in);
        // Read the input number
        int number = scanner.nextInt();
        
        // First determine if the number is even or odd
        if (number % 2 != 0) {
            // Odd number
            System.out.println("Weird");
        } else {
            // Even number, now check the specific ranges
            if (number >= 2 && number <= 5) {
                System.out.println("Not Weird");
            } else if (number >= 6 && number <= 20) {
                System.out.println("Weird");
            } else {
                System.out.println("Not Weird");
            }
        }
		// Close to free up memory
        scanner.close();
	}
}

Commenting on Alterations

While we have done our best to maintain similarity to the template code provided in the original problem, the following changes have been made to follow best practices:

  • Renamed variable n:

    Using more descriptive names improves the clarity of the code and makes it easier for anyone reading the code to understand what each variable represents.