简体   繁体   中英

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!

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

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

    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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM