Hi, So I\'m stuck in this Practice IT problem. I don\'t know where to start or h
ID: 649383 • Letter: H
Question
Hi,
So I'm stuck in this Practice IT problem. I don't know where to start or how to write it. Please help!!
Write a static method named collapseSpaces that accepts a Scanner representing a file as a parameter and writes that file's text to the console, with multiple spaces or tabs reduced to single spaces between words that appear on the same line. For example, if aScanner variable named input is reading an input file containing the following text:
then the call collapseSpaces(input); should produce the following output:
Each word is to appear on the same line in output as it appears in the file. Notice that lines can be blank.
Explanation / Answer
/**
* Java program that opens a text file sample.txt
* that contains lines of leading white spaces and tabs
* Then removes the extra white spaces with single
* space and print on console
*
* */
//RemoveSpaces.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class RemoveSpaces
{
public static void main(String[] args)
{
//declare File and Scanner class variables
File file=null;
Scanner input=null;
try
{
//open a file using File object
file=new File("sample.txt");
//create an instance of Scanner class
input=new Scanner(file);
//calling the static method collapseSpaces that removes the extra white
//spaces
collapseSpaces(input);
//close the input object of Scanner class
input.close();
}
catch (FileNotFoundException e)
{
System.out.println("File not found");
}
}
//The method collapseSpaces that accepts the Scaner object
//as input argument that reads the text lines from the file
//and removes all white spaces and prints the lines on console
//without extra white spaces
private static void collapseSpaces(Scanner input)
{
//Read lines from the input scanner object
while(input.hasNextLine())
{
String line=input.nextLine();
//call trim method that removes the non-printing characters from line
//and leading whitespaces
line=line.trim();
//Replace all extra white spaces with single space
//using replaceAlll method
line=line.replaceAll("\s+"," ").trim();
System.out.println(line);
}
}
}
---------------------------------------------------------------------------
sample text file "sample.tx"
four score and
seven years ago our
fathers brought forth
on this continent
a new
nation
---------------------------------------------------------------------------
Sample output:
four score and
seven years ago our
fathers brought forth
on this continent
a new
nation
Hope this helps you
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.