SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
File Processing
Exercise:
Exercises
Question:7 | ISBN:9780136091813 | Edition: 2

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

// 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

 

0 0

Discussions

Post the discussion to improve the above solution.