Advertisement
jbn6972

TextAlignment

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