Suppose you are given a text file that contains the names of people. Every name
ID: 3634495 • Letter: S
Question
Suppose you are given a text file that contains the names of people. Every name in the file consists of a first name and last name. Unfortunately, the programmer that created the file of names had a strange sense of humor and did not guarantee that each name was on a single line of the file. Read this file of names and write them to a new text file, one full name (both first name and last name) per line.
For example, if the input file contains:
Bob Jones Fred
Charles Ed
Marston Jeff
Williams Ken
Smith Tom Lorry
The output file should be:
Bob Jones
Fred Charles
Ed Marston
Jeff Williams
Ken Smith
Tom Lorry
The program must be done completely how i asked in order for me to get all points. Also include comments(//) explaining what each code does. Thanks!!!
Explanation / Answer
// Needed for BufferedReader import java.io.BufferedReader; // Needed for BufferedWriter import java.io.BufferedWriter; // Needed for FileReader import java.io.FileReader; // Needed for FileWriter import java.io.FileWriter; // The exceptions import java.io.FileNotFoundException; import java.io.IOException; public class test { // We assume that the input file is in the current directory and is named // "in.txt". Output will be to the file "out.txt" in the current directory. public static void main (String args[]) throws FileNotFoundException, IOException { // This we will use to read the text file. BufferedReader in = new BufferedReader (new FileReader ("in.txt")); // This will be our output file. BufferedWriter out = new BufferedWriter (new FileWriter ("out.txt")); // This will contain the line of input. String inputLine; // Whether or not the name we are processing is a first name. boolean isFirst = true; // The name we are processing. String[] names; // A counter. int i; // Now comes the fun part. We enter a while loop which will read // each line of the input file. When we come up with a null value from // the reading operation, we'll stop, as we've reached the end of the // file. while ((inputLine = in.readLine()) != null) { // We only want to process the names if the line is non-empty. if (inputLine.length() > 0) { // Split the input line up into the names. Here we're using // String.split(), which uses a regular expression by which // to split the strings. For more information on this, // go to http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29 // We split the string on one or more consecutive whitespace // characters. names = inputLine.split ("\s+"); // Now let's output the name to the file. for (i = 0; iRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.