Aligning strings in console and Implementing Basic Command Line Behavior


Aligning strings in console

The method PrintWriter.format (called through System.out.format) can be used to print aligned strings in console. The method receives a String with the format information and a series of objects to format:

String dataEntries[] = new String[] {"A",
                                     "BCD",
                                     "EFGHIJ",
                                     "KLMNOPQR"};
 
String format1 = "%-4s"; // min 4 characters, left aligned
String format2 = "%-6.9s"; // min 6 and max 9 characters, left aligned
String format3 = "%7.7s"; // fixed size 7 characters, right aligned
String formatInfo = format1 + " " + format2 + " " + format3;
for(int i = 0; i < dataEntries.length; i++) {
      System.out.format(formatInfo, dataEntries[i], dataEntries[i], dataEntries[i]);
      System.out.println();
}

Output:

A    BCD     EFGHIJK
BCD  BCD     EFGHIJK
EFGH EFGHIJK KLMNOPQ
KLMN KLMNOPQ KLMNOPQ

Using format strings with fixed size permits to print the strings in a table-like appearance with fixed size columns:

String data[] = new String[] {"A",
                              "BCD",
                              "EFGHIJ",
                              "KLMNOPQR"};
 
String format1 = "%-4.4s"; // fixed size 4 characters, left aligned
String format2 = "%-9.9s"; // fixed size 9 characters, left aligned
String format3 = "%7.7s"; // fixed size 7 characters, right aligned
String customFormat = format1 + " " + format2 + " " + format3;
 
for (int i = 0; i < data.length; i++) {
     System.out.format(customFormat, data[i], data[i], data[i]);
     System.out.println();
}

Output:

A    BCD       EFGHIJ
BCD  BCD       EFGHIJ
EFGH EFGHIJ    KLMNOPQ
KLMN KLMNOPQR 

Implementing Basic Command-Line Behavior

For basic prototypes or basic command-line behavior, the following loop comes in handy.

public class CustomCli {
    private static final String CLI_PROMPT = "custom-cli>"; // custom console-like string
    private static final String CMD_EXIT = "exit"; // string for exiting the program
    private static final String CMD_GREET = "greet"; // string for printing a greeting
    private static final String CMD_RESULT = "result"; // string for printing a result
 
    public static void main(String[] args) {
        CustomCli customCli = new CustomCli(); // creates an object of this class
        try {
            customCli.start(); // calls the start function to handle the console-like interaction
        } catch (IOException e) {
            e.printStackTrace(); // prints the exception log if there's an issue with user input
        }
    }
 
    private void start() throws IOException {
        String command = "";
 
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (!command.equals(CMD_EXIT)) { // terminates console if user input is "exit"
            System.out.print(CLI_PROMPT); // prints the custom console-like string
            command = reader.readLine(); // takes input from the user. user input should be started with
                                          // "greet", "result", or "exit"
            String[] commandArray = command.split(" ");
            if (commandArray[0].equals(CMD_GREET)) { // executes when user input starts with "greet"
                greet(commandArray);
            } else if (commandArray[0].equals(CMD_RESULT)) { // executes when user input starts with "result"
                result(commandArray);
            }
        }
    }
 
    // prints a greeting on the screen if user input starts with "greet"
    private void greet(String[] commandArray) {
        System.out.println("Hello, User!");
    }
 
    // prints a result on the screen if user input starts with "result"
    private void result(String[] commandArray) {
        System.out.println("The result is: 42");
    }
}

Basic Programs