Reputation: 23
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
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
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
Reputation: 68715
There are two ways to test this:
Upvotes: 0
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