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!
-
Some reading would be prudent: docs.oracle.com/javase/tutorial/getStarted/application/… , csis.pace.edu/~bergin/KarelJava2ed/ch2/javamain.html , java67.blogspot.com/2012/08/…user2864740– user28647402014年06月19日 00:01:01 +00:00Commented Jun 19, 2014 at 0:01
-
1(One question at a time.. and make sure it's reflected in the title.)user2864740– user28647402014年06月19日 00:05:06 +00:00Commented Jun 19, 2014 at 0:05
4 Answers 4
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
Comments
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
Comments
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.
Comments
There are two ways to test this:
- Introduce a main method in your class and call your generate method from main.
- Add a unit test framework jars and write a unit test class & methods for this.