In: Computer Science
Write a program to reverse the lines of a file and to reverse the words plus the letter's of each word within each line using ArrayList.
A file name mobydick.txt
Example:
Original file contains the following
MOBY DICK; OR THE WHALE
by Herman Melville
CHAPTER 1
Loomings.
Out put should be
.sgnimooL
1 RETPAHC
ellivleM namreH yb
ELAHW EHT RO ;KCID YBOM
its for java eclipse
Solution
Steps :
1.Create an empty arraylist to typee string
2.Take Input file from your system (Donot forgot to add the full address of the file in the address)
3.Iterate each line of the file and add it to the arraylist.
4.Now for each string in arraylist iterate it from back to top (length-1 to 0)
5.For every string we found after reversal our final step is to reverse the strinn using the reverse function in StringBuffer Java Class.
6.At last print to next line after each index of arraylist.
Java Prograam :
/* importing the util package*/
import java.io.*;
import java.util.*;
public class ReverseFile
{
/* main function */
public static void main (String[]args) throws
FileNotFoundException
{
/* creating the arraylist for storing the words in the string
*/
ArrayList < String > reverseFileWords = new ArrayList
<> ();
/*taking the input from the file
* you have to replace the txt file address with your own full
address of the file in your system*/
//TODO
Scanner input =
new Scanner (new File ("-----replace with our own txt file
URL------"));
/* iterating the file for every line */
while (input.hasNextLine ())
{
/* adding the seperate line in the linked list
*/
reverseFileWords.add (input.nextLine ());
}
/* this loop seperate the each word from the line
* we are seperating on the basics of the space*/
for (int i = (reverseFileWords.size () - 1); i >= 0; i--)
{
String ar[] = reverseFileWords.get (i).split ("
");
for (int j = (ar.length - 1); j >= 0; j--)
{
/* reversing each word by using the string buffer
*/
StringBuffer buffer = new StringBuffer (ar[j]);
System.out.print (buffer.reverse () + " ");
}
/* printing the nexr line */
System.out.println (" ");
ar = null;
}
}
}
Code screenshot.
Output ScreenShot :