Stdin and Stout I - Java Solution


Problem Overview

Original Problem: Stdin and Stdout I | Hackerrank

Difficulty: Easy

Category: Input / Output

Description: This beginner-level Java exercise introduces how to read from standard input (stdin) and write to standard output (stdout). You’ll be given three integer inputs, one after the other, and your task is to print each of them on its own line. This problem is designed to help you get comfortable with Java’s Scanner class.

Understanding the Problem

You're asked to read 3 integers from standard input and print each of them on its own line. The purpose here isn’t complex logic — it's to get familiar with reading input and writing output in Java, specifically with Java’s Scanner class.

Input:

Three separate lines of input, each containing an integer.

Output:

Each integer should be printed on its own line, in the same order it was read.

Initial Reasoning

This is a basic I/O problem. We don’t need to do any calculations, just:

  • Read integers

  • Print them in order

We’ll use the Scanner class, which is common for reading input in beginner Java programs.

Pseudocode

// Main program
Read first integer
Read second integer
Read third integer

Print first integer
Print second integer
Print third integer

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 from standard input
        Scanner scanner = new Scanner(System.in);

        // Read three integers representing user inputs
        int firstNumber = scanner.nextInt();
        int secondNumber = scanner.nextInt();
        int thirdNumber = scanner.nextInt();

        // Print each integer on a new line
        System.out.println(firstNumber);
        System.out.println(secondNumber);
        System.out.println(thirdNumber);

        // Always close resources 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 a:

    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.

  • Closing the Scanner after its use:

    While not strictly required by HackerRank, it's important to close resources such as I/O streams to avoid memory leaks, especially in larger programs.