Modify the preceding wordWrap method so that it only wraps whole words, never chopping a word in half. Assume that a word is any whitespace-separated token and that all words are under 60 characters in length.
// package chap456;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordWrap3 {
public static void wordWrap3(Scanner input) {
// this loop continous as long as input has next line
while (input.hasNextLine()) {
String inputLine = input.nextLine();
//
while (inputLine.length() > 60) {
int maxLength = 60;
// if there's no white space at max length, set max length to -1
while (!Character.isWhitespace(inputLine.charAt(maxLength)))
maxLength -= 1;
// create substring from 0 to max length
System.out.println(inputLine.substring(0, maxLength));
while (maxLength < inputLine.length() && Character.isWhitespace(inputLine.charAt(maxLength)))
maxLength += 1;
inputLine = inputLine.substring(maxLength);
}
System.out.println(inputLine);
}
}
// driver method
public static void main(String[] args) throws FileNotFoundException {
// give the path acc to your system
String str = System.getProperty("user.dir") + "\\resources\\wordwrap3.txt";
File file = new File(str);
Scanner input = new Scanner(file);
wordWrap3(input);
}
}
input file: wordwrap3.txt
Black holes are some of the strangest and most fascinating objects in outer space. They're extremely dense, with such strong gravitational attraction that even light cannot escape their grasp if it comes near enough.
Output:
Black holes are some of the strangest and most fascinating
objects in outer space. They're extremely dense, with such
strong gravitational attraction that even light cannot
escape their grasp if it comes near enough.