Submit Chapter6.java with a public static method named justifyText that accepts
ID: 3762374 • Letter: S
Question
Submit Chapter6.java with a public static method named justifyText that accepts two parameters; a Scannerrepresenting a file as the first parameter, and an int width specifying the output text width. Your method writes the text file contents to the console in full justification form.
. For example, if a Scanner is reading an input file c ). For example, if a Scanner is reading an input file containing the following text: Four seven fathers brought score and years ago our forth on this continent new nation. Then a call to justifyText(input, 30 will output the following to the console: Four score and seven years ago our fathers brought forth on this continent a new nation.Explanation / Answer
/**The java program Chapter6 that opens a input file "input.txt"
* file and calls the metod justifyText and prints
* the words from the text of a width 30*/
//Chapter6.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Chapter6
{
public static void main(String[] args)
{
Scanner scanner=null;
final int width=30;
try
{
//open an input text file "input.txt"
scanner=new Scanner(new File("input.txt"));
//calling justifyText method
justifyText(scanner, width);
}
catch (FileNotFoundException e)
{
System.out.println(e);
}
}
/**The method justifyText takes an input parameters
* Scanner object and widht and then prints text line of widht
* 30*/
public static void justifyText(Scanner scanner, int width)
{
//set variables to intial variables
int totalSize=0;
int wordCount=0;
int spaceCount=1;
String word=scanner.next();
while(scanner.hasNext())
{
//count total word size
wordCount+=word.length();
//count total spaces
spaceCount++;
//calcualte totalSize
totalSize=wordCount+spaceCount;
//Check if totalSize is greater than or equalt to width
//reset the word ,space and total size variables
if(totalSize==width)
{
//print a new line and
System.out.println();
System.out.printf("%s ",word);
//reset
wordCount=0;
spaceCount=0;
totalSize=0;
}
else if(totalSize>=width)
{
//print a word
System.out.printf("%s ",word);
//print a new line
System.out.println();
//reset
wordCount=0;
spaceCount=0;
totalSize=0;
}
else
//print the word to console
System.out.printf("%s ",word);
word=scanner.next();
}
System.out.printf("%s",word);
}
}
-----------------------------------------------------------------------------------------------------------------------------
Sample input.txt
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.
Note: on second line the count of words and space are below 30 in size.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.