Question
Given the starter file (FlipLines.java), write a method called flipLines that accepts a Scanner for an input file and writes to the console the same
Given the starter file (FlipLines.java), write a method called flipLines that accepts a Scanner for an input file and writes to the console the same files contents with each pair of lines reversed in order. If the file contains an odd number of lines, leave the last line unmodified. Fill in starter code where it says TODO. For example, if the file contains:
A donkey named Eeyore is his friend, and Kanga and little Roo There's Rabbit and Piglet, and there's Owl But most of all, Winnie the Pooh
your method should produce the following output:
There's Rabbit and Piglet, and there's Owl A donkey named Eeyore is his friend, and Kanga and little Roo But most of all, Winnie the Pooh
import java.io.*; import java.util.*;
/** * Flips the order of pairs of lines *
*/ public class FlipLines {
/** * Starts the program * * @param args array of command line arguments */ public static void main(String[] args) { userInterface(); }
/** * Interface with the user */ public static void userInterface() { Scanner console = new Scanner(System.in); Scanner fileScanner = getInputScanner(console); flipLines(fileScanner); }
/** * Flips the order of pairs of lines in input. If the file contains an odd * number of lines, leave the last line unmodified. * * @param input Scanner for the input file */ public static void flipLines(Scanner input) { // TODO: Complete method }
/** * Reads filename from user until the file exists, then return a file * scanner * * @param console Scanner that reads from the console * * @return a scanner to read input from the file */ public static Scanner getInputScanner(Scanner console) { System.out.print("Enter a file name to process: "); File file = new File(console.next()); while (!file.exists()) { System.out.print("File doesn't exist. " + "Enter a file name to process: "); file = new File(console.next()); } Scanner fileScanner = null;// null signifies NO object reference // while (result == null) { try { fileScanner = new Scanner(file); } catch (FileNotFoundException e) { System.out.println("Input file not found. "); System.out.println(e.getMessage()); System.exit(1); } return fileScanner; }
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started