Java Output Formatting - Solution


Problem Overview

Original Problem: Java Output Formatting | Hackerrank

Difficulty: Easy

Category: Input/Output Formatting

Description: This is an exercise in using Java’s System.out.printf() to format output in a clean and consistent manner. Given a string and a number, format them so the string is left-aligned in a 15-character field, and the number is zero-padded to always display three digits.

Understanding the Problem

The problem is asking us to take a string and an integer and format them according to their type.

Input:

Several lines of text, each containing:

  • A string with up to 10 alphabetic characters

  • An integer between 0 and 999

Output:

For each line of input:

  • Format the string so that it is left-aligned and padded to take up exactly 15 spaces

  • Format the integer so that it is right-aligned and always shows 3 digits

  • Print the formatted text

Initial Reasoning

In the original problem, we are given the wider program structure, which includes a loop and extra formatting. Since the input handling is already done, the focus is entirely on practising formatted output.

Pseudocode

// Main function:
Print leading line
For each of the three input lines
	Read the string 
	Read the integer 
	Format the string and integer and print them 
Print the closing line 

Solution Code

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

public class Solution {
    public static void main(String[] args) {
        // Scanner to read input
        Scanner scanner = new Scanner(System.in);
        System.out.println("================================");

        // Loop exactly 3 times, since the problem guarantees 3 lines
        for (int i = 0; i < 3; i++) {
            // Read the string and integer
            String inputString = scanner.next();   
            int inputInteger = scanner.nextInt();    

            // Format and print the output:
            // %-15s -> left-align the string in 15-character width
            // %03d  -> format integer with 3 digits, pad with zeros
            System.out.printf("%-15s%03d\n", inputString, inputInteger);
        }
        
        System.out.println("================================");
        
        // 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 variables:

    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.