Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.util.Scanner;
- /**
- * Created by: John Nixon (230013111)
- * This class provides functionality to align and justify text in various ways.
- */
- public class TextAlignment {
- /**
- * The main method that reads input from the command line and processes the text.
- * @param args Command line arguments: <filename> <alignmentType> <lineLength>
- */
- public static void main(String[] args) {
- // Validate input arguments and print usage message if invalid
- if (args.length != 3 || !args[1].equals("left") && !args[1].equals("right") && !args[1].equals("centre")
- && !args[1].equals("justify") || !args[2].matches("[0-9]+") || Integer.parseInt(args[2]) < 1) {
- System.out.println("usage: java TextAlignment <filename> <alignmentType> <lineLength>");
- return;
- }
- String fileName = args[0];
- String alignmentType = args[1];
- int lineLength = Integer.parseInt(args[2]);
- // Read text from file and process each paragraph
- try {
- Scanner textScanner = new Scanner(new File(fileName));
- while (textScanner.hasNextLine()) {
- String paragraph = textScanner.nextLine();
- String formattedParagraph = "";
- // Process paragraph based on alignment type
- if(alignmentType.equals("justify")){
- formattedParagraph = justifyText(paragraph, lineLength);
- } else {
- formattedParagraph = alignText(paragraph, alignmentType, lineLength);
- }
- System.out.print(formattedParagraph);
- }
- textScanner.close();
- } catch (FileNotFoundException e) {
- System.out.println("File not found: " + fileName);
- }
- }
- /**
- * Justify the text with the specified line length.
- * @param text The input text to be justified.
- * @param lineLength The length of each line.
- * @return The justified text.
- */
- private static String justifyText(String text, int lineLength) {
- String letters = text.trim(); // Remove leading and trailing spaces
- StringBuilder result = new StringBuilder(); // Stores the justified text
- StringBuilder line = new StringBuilder(); // Temporarily holds a line of text
- int lineChars = 1; // Initialize character count in line
- line.append(letters.charAt(0)); // Add first character to line
- ++lineChars; // Increment character count
- for(int i = 1; i < letters.length() - 1; i++) {
- char c, n, p; // Current, Next, Previous characters
- p = letters.charAt(i - 1);
- c = letters.charAt(i);
- n = letters.charAt(i + 1);
- boolean extra = false; // Tracks if an extra character needs to be added
- // Handle special cases for first character
- if (lineChars == 1 && c == ' '){
- continue; // Skip leading spaces
- }
- if (lineLength > lineChars) {
- line.append(c); // Add character to line if it fits
- ++lineChars; // Increment character count
- } else {
- // Line is full, apply justification logic
- if (p != ' ' && c != ' ' && n != ' '){
- line.append("-"); // Add hyphen to continue word on next line
- extra = true;
- } else if (p == ' ' && c != ' ' && n != ' '){
- line.append(" "); // Add space to end the line
- extra = true;
- } else if (p != ' ' && c != ' ' && n == ' '){
- line.append(c);
- } else if (p != ' ' && c == ' ' && n != ' '){
- line.append(c);
- } else {
- line.append(c);
- }
- result.append(line.toString().trim()).append("\n"); // Add justified line to result
- line.setLength(0);
- lineChars = 1;
- if (extra){
- line.append(c); // Add extra character to new line
- ++lineChars;
- }
- }
- }
- line.append(letters.charAt(letters.length() - 1)); // Add last character to line
- if(line.length() > 0){
- result.append(line.toString().trim()).append("\n"); // Add last justified line to result
- }
- return result.toString(); // Convert result to string and return
- }
- /**
- * Aligns text based on alignment type and line length.
- *
- * @param text The input text to be aligned.
- * @param alignmentType The type of alignment.
- * @param lineLength The length of each line.
- * @return The aligned text.
- */
- private static String alignText(String text, String alignmentType, int lineLength) {
- String[] words = text.split("\\s+"); // Split text into words
- StringBuilder result = new StringBuilder(); // Stores the aligned text
- StringBuilder line = new StringBuilder(); // Temporarily holds a line of text
- int lineChars = 0; // Tracks the number of characters in the current line
- for (String word : words) {
- if (lineChars + word.length() <= lineLength) {
- // Add word to line if it fits within the line length
- line.append(word).append(" ");
- lineChars += word.length() + 1; // Update character count in line
- } else if (word.length() > lineLength) {
- // Handle words longer than the line length
- if (lineChars > 0) {
- result.append(formatLine(line.toString().trim(), alignmentType, lineLength)).append("\n");
- line.setLength(0); // Reset line buffer
- lineChars = 0; // Reset character count in line
- }
- result.append(word.trim()).append("\n"); // Add word directly to result
- } else {
- // Add line to result and start new line with the word
- result.append(formatLine(line.toString().trim(), alignmentType, lineLength)).append("\n");
- line.setLength(0); // Reset line buffer
- lineChars = 0; // Reset character count in line
- line.append(word).append(" ");
- lineChars += word.length() + 1; // Update character count in line
- }
- }
- if (line.length() > 0) {
- // Add any remaining content in the line buffer to the result
- result.append(formatLine(line.toString().trim(), alignmentType, lineLength)).append("\n");
- }
- return result.toString(); // Convert result to string and return
- }
- /**
- * Format a line of text based on the alignment type and line length.
- * @param line The input line of text.
- * @param alignmentType The type of alignment.
- * @param lineLength The length of each line.
- * @return The formatted line of text.
- */
- private static String formatLine(String line, String alignmentType, int lineLength) {
- int spacesToAdd = lineLength - line.length(); // Calculate the number of spaces to add
- if (alignmentType.equals("right") && spacesToAdd > 0) {
- // Right align: Add spaces before the line
- return " ".repeat(spacesToAdd) + line;
- } else if (alignmentType.equals("centre")) {
- // Center align: Divide spaces evenly on both sides
- int rightSpaces = spacesToAdd / 2;
- int leftSpaces = spacesToAdd - rightSpaces;
- return " ".repeat(leftSpaces) + line + " ".repeat(rightSpaces);
- }
- return line; // Left align (default), return the line as is
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement