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

Question

Write a method called collapseSpaces that accepts a Scanner representing an input file as its parameter, then reads that file and outputs it with all its tokens separated by single spaces, collapsing any sequences of multiple spaces into single spaces. For example, consider the following text:
many     spaces    on    this     line!
If this text were a line in the file, the same line should be output as follows:
many spaces on this line!

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

// package chap456;

import java.io.File;
import java.util.Scanner;

public class CollapseSpace {

    public void collapseSpace() {

        // give source file path
        File file = new File("${ystempath}\\textInput.txt");
        // push the File object in scanner constructor
        Scanner input = new Scanner(file);
        // reads the string from the source file
        String string = input.nextLine();
        // below methods multiple spaces with single space and trim the spaces at
        // beginning and ending
        String str1 = string.replaceAll("( +)", " ").trim();
        System.out.println(str1);

    }

    public static void main(String[] args) {
        
        // call the method
        CollapseSpace cs = new CollapseSpace();
        cs.collapseSpace();
    }

}

 

inputText.txt file:


don't bash  AI  robots    they'll remember    and copy     your   name   into    their search     list(probably    death    list) once they    take over   humans
Output:

don't bash AI robots they'll remember and copy your name into their search list(probably death list) once they take over humans

 

0 0

Discussions

Post the discussion to improve the above solution.