java only!!!! Write a program that replaces each line of a file with its reverse
ID: 3753746 • Letter: J
Question
java only!!!!
Write a program that replaces each line of a file with its reverse. For example, if you run java Reverse HelloPrinter.java
then the contents of HelloPrinter.java are changed to
retnirPolleH ssalc cilbup
{
)sgra ][gnirtS(niam diov citats cilbup
{
wodniw elosnoc eht ni gniteerg a yalpsiD //
;)"!dlroW ,olleH"(nltnirp.tuo.metsyS
}
}
Explanation / Answer
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class Reverse { public static String reverse(String str) { if(str.isEmpty()) { return ""; } else { return reverse(str.substring(1)) + str.charAt(0); } } public static void main(String[] args) { if (args.length > 0) { File file = new File(args[0]); try { Scanner fin = new Scanner(file); ArrayList lines = new ArrayList(); while (fin.hasNextLine()) { lines.add(fin.nextLine()); } fin.close(); // write to file lines reversed. PrintWriter printWriter = new PrintWriter(args[0]); for(int i = 0; iRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.