VI. (10 points) Suppose a file named \"song.txt\" contains a carol, beginning wi
ID: 3919452 • Letter: V
Question
VI. (10 points) Suppose a file named "song.txt" contains a carol, beginning with the following lines Chestnuts roasting on an open fire Jack Frost nipping at your nose Yuletide carols being sung by the fire Write a main method to print the contents of the file backwards. You may assume all necessary imports, but be sure to handle any possible exceptions. Each letter should be reversed, as well as each line. That is, the last line should print as follows: erif nepo na no gnitsaor stuntsehc CS 3443- SAMPLE FINAL EXAM 7 of 11Explanation / Answer
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class ReverseFilePrint { public static void main(String[] args) { try { Scanner fin = new Scanner(new File("song.txt")); ArrayList list = new ArrayList(); while (fin.hasNextLine()) { list.add(fin.nextLine()); } for(int i = list.size()-1; i >= 0; i--) { String reverse = ""; for(int j = list.get(i).length()-1; j >= 0; j--) { reverse += list.get(i).charAt(j); } System.out.println(reverse); } fin.close(); } catch (FileNotFoundException e) { System.out.println("Can not open song.txt to read"); } } }Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.