Advertisement
jbn6972

TextAlignmentHrutujaFinal

Oct 1st, 2023
656
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 12.71 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.FileNotFoundException;
  3. import java.io.FileReader;
  4. import java.io.IOException;
  5. import java.util.ArrayList;
  6. import java.util.Arrays;
  7. import java.util.List;
  8.  
  9. /**
  10.  * Created by : Hrutuja Patnekar (230013110)
  11.  * A class for text alignment operations.
  12.  */
  13. public class TextAlignment {
  14.     /**
  15.      * Main method for the TextAlignment program.
  16.      *
  17.      * @param args Command-line arguments: <filename> <alignmentType> <lineLength>
  18.      */
  19.     public static void main(String[] args) {
  20.  
  21.         List<String> align = Arrays.asList("left", "right", "centre", "justify");
  22.        
  23.         // Checking if the correct number of arguments and valid alignment and line length are provided.
  24.         if (args.length != 3 || !align.contains(args[1].toLowerCase())
  25.                 || !args[2].matches("[0-9]+")
  26.                 || Integer.parseInt(args[2]) < 1) {
  27.  
  28.             System.out.println("usage: java TextAlignment <filename> <alignmentType> <lineLength>");
  29.             return;
  30.         }
  31.  
  32.         String fileName = args[0];
  33.         String alignment = args[1];
  34.         int lineLength = Integer.parseInt(args[2]);
  35.         String[] input = readFile(fileName);
  36.  
  37.         try {
  38.             // Switch case to select alignment type
  39.             switch (alignment.toLowerCase()) {
  40.                 case "left":
  41.                     for (int i = 0; i < input.length; i++) {
  42.                         printLeftOutput(input[i], lineLength);
  43.                     }
  44.                     break;
  45.                 case "right":
  46.                     for (int i = 0; i < input.length; i++) {
  47.                         printRightOutput(input[i], lineLength);
  48.                     }
  49.                     break;
  50.  
  51.                 case "centre":
  52.                     for (int i = 0; i < input.length; i++) {
  53.                         printCenterOutput(input[i], lineLength);
  54.                     }
  55.                     break;
  56.  
  57.                 case "justify":
  58.                     for (int i = 0; i < input.length; i++) {
  59.                         printJustifyOutput(input[i], lineLength);
  60.                     }
  61.                     break;
  62.             }
  63.  
  64.         } catch (Exception e) {
  65.             System.out.println(e);
  66.         }
  67.  
  68.     }
  69.  
  70.     /**
  71.      * Reads a file and returns its content as an array of paragraphs.
  72.      *
  73.      * @param filename The name of the file to read.
  74.      * @return An array of paragraphs.
  75.      */
  76.     public static String[] readFile(String filename) {
  77.         try {
  78.             // try to read from the specified file and store paragraphs (lines of text
  79.             // with new-line at end) in list and convert list to array for return
  80.             FileReader fr = new FileReader(filename);
  81.             BufferedReader bfr = new BufferedReader(fr);
  82.             ArrayList<String> content = new ArrayList<String>();
  83.             String paragraph = null;
  84.             while ((paragraph = bfr.readLine()) != null) {
  85.                 content.add(paragraph);
  86.             }
  87.             String[] paragraphs = new String[content.size()];
  88.             for (int i = 0; i < content.size(); i++) {
  89.                 paragraphs[i] = content.get(i);
  90.             }
  91.             bfr.close();
  92.             return paragraphs;
  93.         } catch (FileNotFoundException e) {
  94.             System.out.println("File not found: " + e.getMessage());
  95.         } catch (IOException e) {
  96.             System.out.println("I/O Ooops: " + e.getMessage());
  97.         }
  98.         // If an exception occurred we will get to here as the return statement above
  99.         // was not executed
  100.         // so setup a paragraphs array to return which contains the empty string
  101.         String[] paragraphs = new String[1];
  102.         paragraphs[0] = "";
  103.         return paragraphs;
  104.     }
  105.  
  106.     /**
  107.      * Prints the output with right alignment.
  108.      *
  109.      * @param text The input text.
  110.      * @param lgt  The line length.
  111.      */
  112.     public static void printRightOutput(String text, int lgt) {
  113.         StringBuilder alignedText = new StringBuilder();
  114.         String[] words = text.split("\\s");
  115.         StringBuilder currentLine = new StringBuilder();
  116.         int currentLineLength = 0;
  117.  
  118.         for (String word : words) {
  119.             int wordLength = word.length();
  120.  
  121.             if (currentLineLength + wordLength <= lgt) {
  122.                 // Add word to the current line with a space
  123.                 currentLine.append(word).append(" ");
  124.                 currentLineLength += wordLength + 1;
  125.             } else if(wordLength > lgt){  // If word is longer than line length
  126.                 // Add the current line to the aligned text
  127.                 if(currentLineLength > 0){
  128.                     alignedText.append(rightAlign(currentLine.toString().trim(), lgt));
  129.                     alignedText.append("\n");
  130.                 }
  131.                 // Add the new word to the aligned text
  132.                 alignedText.append(word.toString());
  133.                 alignedText.append("\n");
  134.                 currentLine.setLength(0);
  135.                 currentLineLength = 0;
  136.             }
  137.            
  138.             else {
  139.                 // Start a new line and add word to it
  140.                 alignedText.append(rightAlign(currentLine.toString().trim(), lgt));
  141.                 alignedText.append("\n");
  142.                 currentLine.setLength(0);
  143.                 currentLineLength = 0;
  144.                 currentLine.append(word).append(" ");
  145.                 currentLineLength += wordLength + 1;
  146.             }
  147.         }
  148.  
  149.         if(currentLineLength > 0){
  150.             // Add the last line
  151.             alignedText.append(rightAlign(currentLine.toString().trim(), lgt)).append("\n");
  152.         }
  153.         System.out.print(alignedText.toString());
  154.  
  155.     }
  156.  
  157.     /**
  158.      * Right aligns the text.
  159.      *
  160.      * @param text       The input text.
  161.      * @param lineLength The line length.
  162.      * @return The right aligned text.
  163.      */
  164.     public static String rightAlign(String text, int lineLength) {
  165.         // Calulate the number of spaces to add before the words in same line when no
  166.         // more words fit in line
  167.         int spacesToAdd = lineLength - text.length();
  168.         if (spacesToAdd <= 0) {
  169.             return text;
  170.         }
  171.         return " ".repeat(spacesToAdd) + text;
  172.     }
  173.  
  174.     /**
  175.      * Prints the output with left alignment.
  176.      *
  177.      * @param text The input text.
  178.      * @param lgt  The line length.
  179.      */
  180.     public static void printLeftOutput(String text, int lgt) {
  181.  
  182.         String[] words = text.split("\\s");
  183.         StringBuilder alignedText = new StringBuilder();
  184.         int currentLineLength = 0;
  185.  
  186.         for (String word : words) {
  187.             if (currentLineLength + word.length() <= lgt) {
  188.                 // Add word to the current line with a space
  189.                 alignedText.append(word).append(" ");
  190.                 currentLineLength += word.length() + 1;
  191.             }else if(word.length() > lgt){  // If word is longer than line length
  192.                 // Add the current line to the aligned text
  193.                 if(currentLineLength > 0){
  194.                     alignedText.append("\n");
  195.                 }
  196.                 // Add the new word to the aligned text
  197.                 alignedText.append(word.toString());
  198.                 alignedText.append("\n");
  199.                 currentLineLength = 0;
  200.             }
  201.              else {
  202.                 // Start a new line and add word to it
  203.                 alignedText.append("\n").append(word).append(" ");
  204.                 currentLineLength = word.length() + 1;
  205.             }
  206.         }
  207.  
  208.         System.out.println(alignedText.toString().trim());
  209.     }
  210.  
  211.     /**
  212.      * Prints the output with center alignment.
  213.      *
  214.      * @param text The input text.
  215.      * @param lgt  The line length.
  216.      */
  217.     public static void printCenterOutput(String text, int lgt) {
  218.  
  219.         StringBuilder alignedText = new StringBuilder();
  220.         String[] words = text.split("\\s");
  221.         StringBuilder currentLine = new StringBuilder();
  222.         int currentLineLength = 0;
  223.  
  224.         for (String word : words) {
  225.             int wordLength = word.length();
  226.  
  227.             if (currentLineLength + wordLength <= lgt) {
  228.                 // Add word to the current line with a space
  229.                 currentLine.append(word).append(" ");
  230.                 currentLineLength += wordLength + 1;
  231.             }else if(wordLength > lgt){  // If word is longer than line length
  232.                 // Add the current line to the aligned text
  233.                 if(currentLineLength > 0){
  234.                     alignedText.append(centerAlign(currentLine.toString().trim(), lgt));
  235.                     alignedText.append("\n");
  236.                 }
  237.                 // Add the new word to the aligned text
  238.                 alignedText.append(word.toString().trim());
  239.                 alignedText.append("\n");
  240.                 currentLine.setLength(0);
  241.                 currentLineLength = 0;
  242.             }
  243.              else {
  244.                 // Start a new line and add word to it
  245.                 alignedText.append(centerAlign(currentLine.toString().trim(), lgt));
  246.                 alignedText.append("\n");
  247.                 currentLine.setLength(0);
  248.                 currentLine.append(word).append(" ");
  249.                 currentLineLength = wordLength + 1;
  250.             }
  251.         }
  252.  
  253.         // Add the last line
  254.         if(currentLineLength > 0){
  255.             alignedText.append(centerAlign(currentLine.toString().trim(), lgt)).append("\n");
  256.         }
  257.         System.out.println(alignedText.toString());
  258.     }
  259.  
  260.     /**
  261.     * Centers the text.
  262.     *
  263.     * @param text       The input text.
  264.     * @param lineLength The line length.
  265.     * @return The centered text.
  266.     */
  267.     public static String centerAlign(String text, int lineLength) {
  268.         // Calulate the number of spaces to add between the words of the same line when
  269.         // no more words fit in line
  270.         int spacesToAdd = lineLength - text.length();
  271.         int rightSpaces = spacesToAdd / 2;
  272.         int leftSpaces = spacesToAdd - rightSpaces;
  273.         return " ".repeat(leftSpaces) + text + " ".repeat(rightSpaces);
  274.     }
  275.  
  276.     /**
  277.      * Prints the output with justification.
  278.      *
  279.      * @param text The input text.
  280.      * @param lgt  The line length.
  281.      */
  282.     public static void printJustifyOutput(String text, int lineLength) {
  283.         String input = text.trim();
  284.         StringBuilder justifiedText = new StringBuilder();
  285.         StringBuilder currentLine = new StringBuilder();
  286.  
  287.         int lineChars = 1;
  288.         currentLine.append(input.charAt(0));
  289.         ++lineChars;
  290.        
  291.         // Loop through the input string
  292.         for (int i = 1; i < input.length() - 1; i++) {
  293.             char prevChar, currChar, nextChar;
  294.             prevChar = input.charAt(i - 1);
  295.             currChar = input.charAt(i);
  296.             nextChar = input.charAt(i + 1);
  297.  
  298.             // Check if the current character is the last character of the input string    
  299.             boolean extraChar = false;
  300.  
  301.             // Check if the current character is a space and the line contains only one character
  302.             if (lineChars == 1 && currChar == ' ') {
  303.                 continue;
  304.             }
  305.  
  306.             // Check if the current character is a space and the next character is a space
  307.             if (lineLength > lineChars) {
  308.                 currentLine.append(currChar);
  309.                 ++lineChars;
  310.             } else { // If the line contains the maximum number of characters
  311.                 if (prevChar != ' ' && currChar != ' ' && nextChar != ' ') {
  312.                     currentLine.append("-");
  313.                     extraChar = true;
  314.                 } else if (prevChar == ' ' && currChar != ' ' && nextChar != ' ') {
  315.                     currentLine.append(" ");
  316.                     extraChar = true;
  317.                 } else if (prevChar != ' ' && currChar != ' ' && nextChar == ' ') {
  318.                     currentLine.append(currChar);
  319.                 } else if (prevChar != ' ' && currChar == ' ' && nextChar != ' ') {
  320.                     currentLine.append(currChar);
  321.                 } else {
  322.                     currentLine.append(currChar);
  323.                 }
  324.  
  325.                 justifiedText.append(currentLine.toString().trim()).append("\n");
  326.                 currentLine.setLength(0);
  327.                 lineChars = 1;
  328.  
  329.                 if (extraChar) {
  330.                     currentLine.append(currChar);
  331.                     ++lineChars;
  332.                 }
  333.             }
  334.         }
  335.  
  336.         currentLine.append(input.charAt(input.length() - 1));
  337.         if (currentLine.length() > 0) {
  338.             justifiedText.append(currentLine.toString().trim()).append("\n");
  339.         }
  340.        
  341.         System.out.println(justifiedText.toString().trim());
  342.     }
  343.    
  344. }
  345.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement