I have to read in an integer which will be the length of the succeeding lines. (The lines of text will never be longer than the length provided).
I then have to read
I wrote a simple method to justify text. Its not 100% accurate, but works for the most part (since it ignores punctuations completely, and there might be some edge cases missing too). Also, Word justifies text in a richer manner (by not adding spaces to fill up the gap, but evenly distributing the width of a whitespace, which is tricky to do here).
public static void justifyText (String text) {
int STR_LENGTH = 80;
int end=STR_LENGTH, extraSpacesPerWord=0, spillOverSpace=0;
String[] words;
System.out.println("Original Text: \n" + text);
System.out.println("Justified Text: ");
while(end < text.length()) {
if(text.charAt(STR_LENGTH) == ' ') {
// Technically, this block is redundant
System.out.println (text.substring(0, STR_LENGTH));
text = text.substring(STR_LENGTH);
continue;
}
end = text.lastIndexOf(" ", STR_LENGTH);
words = text.substring(0, end).split(" ");
extraSpacesPerWord = (STR_LENGTH - end) / words.length;
spillOverSpace = STR_LENGTH - end + (extraSpacesPerWord * words.length);
for(String word: words) {
System.out.print(word + " ");
System.out.print((extraSpacesPerWord-- > 0) ? " ": "");
System.out.print((spillOverSpace-- > 0) ? " ": "");
}
System.out.print("\n");
text = text.substring(end+1);
}
System.out.println(text);
}