Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a static method named fixSpacing that accepts a Scanner representing a fil

ID: 657662 • Letter: W

Question

Write a static method named fixSpacing 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 the input file contains the following text,

four      score   and

seven              years ago         our

           

fathers brought             forth

    on this          continent

a         new

           

nation

then your method should produce the following output:

four score and

           

seven years ago our

           

fathers brought forth

on this continent

a new

           

nation

Notice that some lines might be blank. Each word is to appear on the same line in the output on which it appears in the input file.

Explanation / Answer

// This program removes excess space in an input file. import java.io.*; import java.util.*; public class FixSpacing { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("words.txt")); PrintStream output = new PrintStream(new File("words2.txt")); while (input.hasNextLine()) { String text = input.nextLine(); echoFixed(text, output); echoFixed(text, System.out); } } public static void echoFixed(String text, PrintStream output) { Scanner data = new Scanner(text); if (data.hasNext()) { output.print(data.next()); while (data.hasNext()) { output.print(" " + data.next()); } } output.println(); } }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote