Write a method in Java called wordWrap that accepts a Scanner representing an in
ID: 3556333 • Letter: W
Question
Write a method in Java 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.
Explanation / Answer
import java.io.File;
import java.util.Scanner;
public class WordWrap
{
public static void wordWrap(Scanner input)
{
while(input.hasNextLine())
{
int i=0;
String line=input.nextLine();
//Scanner scan=new Scanner(line);
if(line.length()<=60)
System.out.println(line);
else
{
for(int j=0; j<line.length(); j++)
{
i++;
System.out.print(line.charAt(j));
if(i==60)
{
i=0;
System.out.println();
}
}
System.out.println();
}
}
}
public static void main(String[] args)
{
Scanner in = null;
try
{
in = new Scanner(new File("input.txt"));
wordWrap(in); // calling method
}
catch(Exception e)
{
System.out.println("File not found");
}
in.close(); // closing input stream.
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.