Slip No 21 Q A

Q.Write a java program to display each word from a file in reverse order. [15 M]

import java.io.*;

class ReverseWordsFile
{
    public static void main(String args[]) throws IOException
    {
        BufferedReader br = new BufferedReader(new FileReader("input.txt"));
        String line;

        while((line = br.readLine()) != null)
        {
            // Split line into words
            String words[] = line.split(" ");

            for(String w : words)
            {
                String rev = "";

                // Reverse each word
                for(int i = w.length()-1; i >= 0; i--)
                {
                    rev += w.charAt(i);
                }

                System.out.print(rev + " ");
            }
            System.out.println();
        }

        br.close();
    }
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top