0

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!

asked Jun 18, 2014 at 23:57
2

4 Answers 4

2

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

answered Jun 19, 2014 at 0:04
Sign up to request clarification or add additional context in comments.

Comments

1

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

answered Jun 19, 2014 at 0:00

Comments

1
 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.

answered Jun 19, 2014 at 0:04

Comments

0

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.
answered Jun 19, 2014 at 0:00

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.