Advertisement
jbn6972

TextAlignment

Sep 22nd, 2023 (edited)
604
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.87 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.util.Scanner;
  4.  
  5. /**
  6.  * Created by: John Nixon (230013111)
  7.  * This class provides functionality to align and justify text in various ways.
  8.  */
  9. public class TextAlignment {
  10.  
  11.     /**
  12.      * The main method that reads input from the command line and processes the text.
  13.      * @param args Command line arguments: <filename> <alignmentType> <lineLength>
  14.      */    
  15.     public static void main(String[] args) {
  16.         // Validate input arguments and print usage message if invalid
  17.         if (args.length != 3 || !args[1].equals("left") && !args[1].equals("right") && !args[1].equals("centre")
  18.                 && !args[1].equals("justify") || !args[2].matches("[0-9]+") || Integer.parseInt(args[2]) < 1) {
  19.             System.out.println("usage: java TextAlignment <filename> <alignmentType> <lineLength>");
  20.             return;
  21.         }
  22.  
  23.         String fileName = args[0];
  24.         String alignmentType = args[1];
  25.         int lineLength = Integer.parseInt(args[2]);
  26.  
  27.         // Read text from file and process each paragraph
  28.         try {
  29.             Scanner textScanner = new Scanner(new File(fileName));
  30.  
  31.             while (textScanner.hasNextLine()) {
  32.                 String paragraph = textScanner.nextLine();
  33.                 String formattedParagraph = "";
  34.                
  35.                 // Process paragraph based on alignment type
  36.                 if(alignmentType.equals("justify")){
  37.                     formattedParagraph = justifyText(paragraph, lineLength);
  38.                 } else {
  39.                     formattedParagraph = alignText(paragraph, alignmentType, lineLength);
  40.                 }
  41.                 System.out.print(formattedParagraph);
  42.             }
  43.  
  44.             textScanner.close();
  45.         } catch (FileNotFoundException e) {
  46.             System.out.println("File not found: " + fileName);
  47.         }
  48.     }
  49.  
  50.     /**
  51.      * Justify the text with the specified line length.
  52.      * @param text The input text to be justified.
  53.      * @param lineLength The length of each line.
  54.      * @return The justified text.
  55.      */
  56.     private static String justifyText(String text, int lineLength) {
  57.         String letters = text.trim(); // Remove leading and trailing spaces
  58.         StringBuilder result = new StringBuilder(); // Stores the justified text
  59.         StringBuilder line = new StringBuilder(); // Temporarily holds a line of text
  60.  
  61.         int lineChars = 1; // Initialize character count in line
  62.         line.append(letters.charAt(0)); // Add first character to line
  63.         ++lineChars; // Increment character count
  64.  
  65.         for(int i = 1; i < letters.length() - 1; i++) {
  66.             char c, n, p; // Current, Next, Previous characters
  67.             p = letters.charAt(i - 1);
  68.             c = letters.charAt(i);
  69.             n = letters.charAt(i + 1);
  70.  
  71.             boolean extra = false; // Tracks if an extra character needs to be added
  72.  
  73.             // Handle special cases for first character
  74.             if (lineChars == 1 && c == ' '){
  75.                 continue; // Skip leading spaces
  76.             }
  77.  
  78.             if (lineLength > lineChars) {
  79.                 line.append(c); // Add character to line if it fits
  80.                 ++lineChars; // Increment character count
  81.             } else {
  82.                 // Line is full, apply justification logic
  83.                 if (p != ' ' && c != ' ' && n != ' '){
  84.                     line.append("-"); // Add hyphen to continue word on next line
  85.                     extra = true;
  86.                 } else if (p == ' ' && c != ' ' && n != ' '){
  87.                     line.append(" "); // Add space to end the line
  88.                     extra = true;
  89.                 } else if (p != ' ' && c != ' ' && n == ' '){
  90.                     line.append(c);
  91.                 } else if (p != ' ' && c == ' ' && n != ' '){
  92.                     line.append(c);
  93.                 } else {
  94.                     line.append(c);
  95.                 }
  96.  
  97.                 result.append(line.toString().trim()).append("\n"); // Add justified line to result
  98.                 line.setLength(0);
  99.                 lineChars = 1;
  100.  
  101.                 if (extra){
  102.                     line.append(c); // Add extra character to new line
  103.                     ++lineChars;
  104.                 }
  105.             }
  106.         }
  107.  
  108.         line.append(letters.charAt(letters.length() - 1)); // Add last character to line
  109.         if(line.length() > 0){
  110.             result.append(line.toString().trim()).append("\n"); // Add last justified line to result
  111.         }
  112.  
  113.         return result.toString(); // Convert result to string and return
  114.     }
  115.  
  116.     /**
  117.      * Aligns text based on alignment type and line length.
  118.      *
  119.      * @param text The input text to be aligned.
  120.      * @param alignmentType The type of alignment.
  121.      * @param lineLength The length of each line.
  122.      * @return The aligned text.
  123.      */
  124.     private static String alignText(String text, String alignmentType, int lineLength) {
  125.         String[] words = text.split("\\s+"); // Split text into words
  126.        
  127.         StringBuilder result = new StringBuilder(); // Stores the aligned text
  128.         StringBuilder line = new StringBuilder(); // Temporarily holds a line of text
  129.         int lineChars = 0; // Tracks the number of characters in the current line
  130.  
  131.         for (String word : words) {
  132.             if (lineChars + word.length() <= lineLength) {
  133.                 // Add word to line if it fits within the line length
  134.                 line.append(word).append(" ");
  135.                 lineChars += word.length() + 1; // Update character count in line
  136.             } else if (word.length() > lineLength) {
  137.                 // Handle words longer than the line length
  138.                 if (lineChars > 0) {
  139.                     result.append(formatLine(line.toString().trim(), alignmentType, lineLength)).append("\n");
  140.                     line.setLength(0); // Reset line buffer
  141.                     lineChars = 0; // Reset character count in line
  142.                 }
  143.                 result.append(word.trim()).append("\n"); // Add word directly to result
  144.             } else {
  145.                 // Add line to result and start new line with the word
  146.                 result.append(formatLine(line.toString().trim(), alignmentType, lineLength)).append("\n");
  147.                 line.setLength(0); // Reset line buffer
  148.                 lineChars = 0; // Reset character count in line
  149.                 line.append(word).append(" ");
  150.                 lineChars += word.length() + 1; // Update character count in line
  151.             }
  152.         }
  153.  
  154.         if (line.length() > 0) {
  155.             // Add any remaining content in the line buffer to the result
  156.             result.append(formatLine(line.toString().trim(), alignmentType, lineLength)).append("\n");
  157.         }
  158.  
  159.         return result.toString(); // Convert result to string and return
  160.     }
  161.  
  162.     /**
  163.      * Format a line of text based on the alignment type and line length.
  164.      * @param line The input line of text.
  165.      * @param alignmentType The type of alignment.
  166.      * @param lineLength The length of each line.
  167.      * @return The formatted line of text.
  168.      */
  169.     private static String formatLine(String line, String alignmentType, int lineLength) {
  170.         int spacesToAdd = lineLength - line.length(); // Calculate the number of spaces to add
  171.        
  172.         if (alignmentType.equals("right") && spacesToAdd > 0) {
  173.             // Right align: Add spaces before the line
  174.             return " ".repeat(spacesToAdd) + line;
  175.         } else if (alignmentType.equals("centre")) {
  176.             // Center align: Divide spaces evenly on both sides
  177.             int rightSpaces = spacesToAdd / 2;
  178.             int leftSpaces = spacesToAdd - rightSpaces;
  179.             return " ".repeat(leftSpaces) + line + " ".repeat(rightSpaces);
  180.         }
  181.         return line; // Left align (default), return the line as is
  182.     }
  183.  
  184. }
  185.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement