How to resolve the algorithm Align columns step by step in the Java programming language
How to resolve the algorithm Align columns step by step in the Java programming language
Table of Contents
Problem Statement
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, or center justified within its column. Use the following text to test your programs:
Note that:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Align columns step by step in the Java programming language
This Java program defines a class ColumnAligner
that aligns fields into columns, separated by the pipe character (|
). It supports left-aligning, right-aligning, and center-aligning columns. The program can be invoked with a file path as the first argument and an optional alignment argument (left, right, or center) as the second argument. If no alignment argument is provided, left alignment is used by default.
The ColumnAligner
class has three main methods:
-
processInputLine(String line)
: This method takes a line of text as input and splits it into words using the dollar sign ($
) as the delimiter. It adds the words to a list of words and updates the maximum number of columns and the widths of each column based on the length of the words. -
align(AlignFunction a)
: This method aligns all the columns in the list of words using the providedAlignFunction
object. TheAlignFunction
interface defines a single method,align(String s, int length)
, which takes a strings
and an integerlength
and returns the aligned string. Thealign
method iterates through all the rows and columns in the list of words and calls thealign
method of theAlignFunction
object to align each word. The aligned words are separated by the pipe character (|
) and joined together into a string, which is returned. -
alignLeft()
,alignRight()
, andalignCenter()
: These methods are convenience methods that call thealign
method with the appropriateAlignFunction
object to align the columns left, right, or center, respectively.
The main
method of the program reads the contents of the specified file and creates a ColumnAligner
object with the lines of text. It then calls the alignLeft()
, alignRight()
, or alignCenter()
method based on the alignment argument and prints the aligned columns to the console.
Here is an example of how to use the ColumnAligner
program:
java ColumnAligner data.txt left
This command will read the contents of the data.txt
file and align the columns left-aligned. The output will be printed to the console.
Source code in the java programming language
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
/**
* Aligns fields into columns, separated by "|"
*/
public class ColumnAligner {
private List<String[]> words = new ArrayList<>();
private int columns = 0;
private List<Integer> columnWidths = new ArrayList<>();
/**
* Initialize columns aligner from lines in a single string
*
* @param s
* lines in a single string. Empty string does form a column.
*/
public ColumnAligner(String s) {
String[] lines = s.split("\\n");
for (String line : lines) {
processInputLine(line);
}
}
/**
* Initialize columns aligner from lines in a list of strings
*
* @param lines
* lines in a single string. Empty string does form a column.
*/
public ColumnAligner(List<String> lines) {
for (String line : lines) {
processInputLine(line);
}
}
private void processInputLine(String line) {
String[] lineWords = line.split("\\$");
words.add(lineWords);
columns = Math.max(columns, lineWords.length);
for (int i = 0; i < lineWords.length; i++) {
String word = lineWords[i];
if (i >= columnWidths.size()) {
columnWidths.add(word.length());
} else {
columnWidths.set(i, Math.max(columnWidths.get(i), word.length()));
}
}
}
interface AlignFunction {
String align(String s, int length);
}
/**
* Left-align all columns
*
* @return Lines, terminated by "\n" of columns, separated by "|"
*/
public String alignLeft() {
return align(new AlignFunction() {
@Override
public String align(String s, int length) {
return StringUtils.rightPad(s, length);
}
});
}
/**
* Right-align all columns
*
* @return Lines, terminated by "\n" of columns, separated by "|"
*/
public String alignRight() {
return align(new AlignFunction() {
@Override
public String align(String s, int length) {
return StringUtils.leftPad(s, length);
}
});
}
/**
* Center-align all columns
*
* @return Lines, terminated by "\n" of columns, separated by "|"
*/
public String alignCenter() {
return align(new AlignFunction() {
@Override
public String align(String s, int length) {
return StringUtils.center(s, length);
}
});
}
private String align(AlignFunction a) {
StringBuilder result = new StringBuilder();
for (String[] lineWords : words) {
for (int i = 0; i < lineWords.length; i++) {
String word = lineWords[i];
if (i == 0) {
result.append("|");
}
result.append(a.align(word, columnWidths.get(i)) + "|");
}
result.append("\n");
}
return result.toString();
}
public static void main(String args[]) throws IOException {
if (args.length < 1) {
System.out.println("Usage: ColumnAligner file [left|right|center]");
return;
}
String filePath = args[0];
String alignment = "left";
if (args.length >= 2) {
alignment = args[1];
}
ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8));
switch (alignment) {
case "left":
System.out.print(ca.alignLeft());
break;
case "right":
System.out.print(ca.alignRight());
break;
case "center":
System.out.print(ca.alignCenter());
break;
default:
System.err.println(String.format("Error! Unknown alignment: '%s'", alignment));
break;
}
}
}
You may also check:How to resolve the algorithm Enforced immutability step by step in the Sidef programming language
You may also check:How to resolve the algorithm Leap year step by step in the Bash programming language
You may also check:How to resolve the algorithm Middle three digits step by step in the Icon and Unicon programming language
You may also check:How to resolve the algorithm Sorting algorithms/Heapsort step by step in the Janet programming language
You may also check:How to resolve the algorithm Four is magic step by step in the Wren programming language