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:9 | ISBN:9780136091813 | Edition: 2

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.