Using Java , Write a method called flipLines that accept a scanner for an input
ID: 3705755 • Letter: U
Question
Using Java , Write a method called flipLines that accept a scanner for an input file and writes to the console the same file's contents with each pair of lines reversed in order. If the file contains an odd number of lines, leave the last line unmodified, for example, if the fole contains: twas brillig and the slithy toves did gyre and gimble in the wabw. All mimsey were the borogroves, and the mome raths outgrabe. your methhod should produce the following output:
What does the cod look like from start to finish and what are your comments?
did gyre and gimble in the wabe.
twas brillig and the
slithy toves and the mome raths outgrabe.
All mimsey were the borogroves,
Explanation / Answer
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) { String line = null; while (input.hasNextLine()) { if(line != null) { System.out.println(input.nextLine()); System.out.println(line); line = null; } else { line = input.nextLine(); } } if(line != null) { System.out.println(line); } } /** * 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; } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.