Read the \"reverse.txt\" file, one line at a time. Print the line reversed. Use
ID: 3552142 • Letter: R
Question
Read the "reverse.txt" file, one line at a time.
Print the line reversed.
Use arraylists.
you cannot use the collections "reverse" method, create your own or put it in code inside a loop.
HINT: use ".add" to re-arrange elements in an arraylist
10 bonus points: use a two dimensional ArrayList of String to read the entire file at once, instead of one line at a time.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
/*
Open the reverse.txt file
*/
public class ReverseFileContents
{
public static void main(String[] args) throws FileNotFoundException
{
//
//
//You need to open the "reverse.txt" file here
//
//
//
while ( inputFile.hasNextLine())
{
//
//Inside the while loop you will get the line of text
// one line at a time.
//
//Next, you will reverse the line and print out the "string"
// of characters on the screen for each line
// to reveal the ACM code of ethics.
//
}
}
}
Explanation / Answer
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.*; class ReverseFileContents { public static void main(String[] args) throws FileNotFoundException { Scanner inputFile = new Scanner(new File("reverse.txt")); ArrayList list = new ArrayList(); while(inputFile.hasNext()) { list.add(inputFile.nextLine()); String s = list.get(list.size()-1); for(int i=s.length()-1; i>=0; i--) System.out.print(s.charAt(i)+" "); System.out.println(); } inputFile.close(); } }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.