OOP-JAVA Practical 25

OOP-JAVA Practical 25
  • Aim: Write a program that reads words from a text file and displays all the nonduplicate words in descending order. The text file is passed as a command-line argument.
  • Code:
    import java.io.File;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Scanner;
    
    public class practical25 {
        public static void main(String[] args) {
            if (args.length != 1) {
            System.out.println("Enter file name as command line argument");
                System.exit(0);
            }
            String filename = args[0];
            String line;
            ArrayList<String> reveList = new ArrayList<String>();
            try {
                Scanner s = new Scanner(new File(filename));
                while ((s.hasNextLine())) {
                    line=s.nextLine();
                    String[] words = line.split("[ ,.]+");
                    for (int i = 0; i < words.length; i++) {
                        /*
                         * add this line of code to convert all words in lowercase
                         * "String str=words[i].toLowerCase();" 
                         * and in this for loop change words[i] to str to get all words in lowercase.
                         */
                        if (reveList.contains(words[i])) {
                            continue;
                        } else {
                            reveList.add(words[i]);
                        }
                        /* change upto here for getting words in lowercase */
                    }
                }
                s.close();
            } catch (Exception e) {
                System.out.println(e);
            }
            Collections.sort(reveList, Collections.reverseOrder());
            System.out.println(reveList);
        }
    }
  • Output:
    Output of practical 25

Comments