user3754524
user3754524

Reputation: 23

How to run program from command line?

I am trying to write random numbers to a file. SO basically one number on each line and the method name takes the filepath argument and long n argument which is the number of random numbers generated. This is what I have so far:

public  void generate(long n, String filePath) throws FileNotFoundException  
    {
        PrintWriter out = new PrintWriter("filePath");
        Random r = new Random();
        for(int i = 0; i < n; i++)
        {
            int num = r.nextInt(10);
            out.write(num + "\n");
        }

        out.close();
    }

Am I on the right track? Also how would I go about running this program via cmd. I know the commands for compiling and running it but I think I need a tester to run this. So could somebody give me instructions on how I could go about running this code via cmd.

Edit: Got it working! Thanks everyone for the help!

Upvotes: 0

Views: 135

Answers (4)

clearlyspam23
clearlyspam23

Reputation: 1694

you're close with your printing. Instead of doing

out.write(num + "\n");

youll instead want to do

out.println(num);

which is cross platform (and in my opinion, easier to read).

Additionally, in order to run your program from command line, all you'll need to do is add a main method in your class, like so

public static void main(String[] args) throws FileNotFoundException  {
    int n = Integer.parseInt(args[0]);
    String filePath = args[1];
    YourClass c = new YourClass();
    c.generate(n, filePath);

}

this main assumes you're passing in 2 parameters from command line, the number followed by the filename

Hope this was helpful

Upvotes: 2

Mike Elofson
Mike Elofson

Reputation: 2037

    PrintWriter out = new PrintWriter("filePath");

Should be

    PrintWriter out = new PrintWriter(filePath);

You want to use the variable name in the parameters, what you were passing instead is a string.

Upvotes: 1

Juned Ahsan
Juned Ahsan

Reputation: 68715

There are two ways to test this:

  1. Introduce a main method in your class and call your generate method from main.
  2. Add a unit test framework jars and write a unit test class & methods for this.

Upvotes: 0

Nivas
Nivas

Reputation: 18334

filePath is a variable that holds the path of the file, so you don't want to enclose it in double quotes. If you do, it is treated as a String, so the program searches for a file with path filePath.

PrintWriter out = new PrintWriter(filePath); // no ""

The "tester" can run the program the same way you run it: java programName

Upvotes: 1

Related Questions