0

Okay, first post, yay! Now I know this topic has been beaten to death already. But here's the question :

Write a program that reads words separated by spaces from a text file and displays words in ascending order. (If two words are the same, display only one). Pass the text filename from the command line. Assume that the text file contains only words separated by spaces.

Now I have the reading from the file part figured out. But how do I "pass the filename from the command line"? And then there's the uniqueness factor.

Help?

Edit: Thanks guys for your help. Here's where I stand now:

import java.io.*;
import java.util.*;

public class Splittext {
    public static void main(String[] args) {
        String fileName = args[0];
        Scanner s = null;

        try {
            s = new Scanner(new BufferedReader(new FileReader(fileName)));
                while (s.hasNext()) {
                    System.out.println(s.next());
                }
            } catch (FileNotFoundException fnfe) {
            System.exit(0);
        } finally {
               if (s != null) {
                   s.close();
                }
            }


       TreeSet<String> ts = new TreeSet<String>();

       ts.add(s);

       Iterator it = ts.iterator();

       while(it.hasNext()) {
           String value = (String)it.next();
           System.out.println("Result :" + result);
        }
    }        
}

But this yields : No suitable method for add (java.util.Scanner); method java.util.TreeSet.add(java.lang.String) is not applicable.

Sorry for the noob questions! Really appreaciate the help :)

A C
  • 417
  • 3
  • 5
  • 17

3 Answers3

3

Do like this.

public static void main(String args[]) {
    String fileName = args[0];
    Scanner s = null;

    try {
        s = new Scanner(new BufferedReader(new FileReader(fileName));

        while (s.hasNext()) {
            System.out.println(s.next());
        }
    } finally {
        if (s != null) {
            s.close();
        }
    }
}

Run this like

java classname readthisfile.txt
Ajay S
  • 48,003
  • 27
  • 91
  • 111
0

But how do I "pass the filename from the command line"?

public static void main(String args[])
{
    final String filename = args[0];
    // ...
}

And then there's the uniqueness factor.

And sorting factor.

  1. Insert all the words into TreeSet.
  2. Iterate through it and print values. They will be sorted and unique.
Adam Stelmaszczyk
  • 19,665
  • 4
  • 70
  • 110
0

Your main function has String[] args passed into to it when you kick off your application, this is where you access you input arguments.

e.g.:

java -cp . my.class.Example Happy Days

Would see the Example class receiving this:

public static void main(String[] args) {
  // args.length == 2
  // args[0] = "Happy"
  // args[1] = "Days"
}
Chris Cooper
  • 4,982
  • 1
  • 17
  • 27