Write a method called wordWrap that accepts a Scanner representing an input file as its parameter and outputs each line of the file to the console, word-wrapping all lines that are longer than 60 characters. For example, if a line contains 112 characters, the method should replace it with two lines: one containing the first 60 characters and another containing the final 52 characters. A line containing 217 characters should be wrapped into four lines: three of length 60 and a final line of length 37.
// package chap456;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordWrap {
public static void wordWrap(Scanner input) {
// if the input contains next line
while(input.hasNextLine()) {
String inputline = input.nextLine();
// this loop continous as long as substring has length greater than 60
while(inputline.length() > 60) {
// the substring method takes beginning index and ending index as
// it's parameteres
System.out.println(inputline.substring(0, 60));
// and make substring out of it
inputline = inputline.substring(60);
}
System.out.println(inputline);
}
}
public static void main(String[] args) throws FileNotFoundException {
String str = System.getProperty("user.dir") +"\\resources\\wordwrap.txt";
File file = new File(str);
Scanner input = new Scanner(file);
wordWrap(input);
}
}
FileName: wordwrap.txt
kdfalfasfjdoturosirteosglksjdgjdsoeituorgldskjldgooweidsjflgksldkglasjdflkajlfdfalkjoiurogsdgjlksjdlgfkjsgoreoirtwoieurtpoijdf;lkajfdfjlkjokjhsdfkdhjhkgjhsakahafafashfkda
Output:
kdfalfasfjdoturosirteosglksjdgjdsoeituorgldskjldgooweidsjflg
ksldkglasjdflkajlfdfalkjoiurogsdgjlksjdlgfkjsgoreoirtwoieurt
poijdf;lkajfdfjlkjokjhsdfkdhjhkgjhsakahafafashfkda