[英]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. 因此,基本上每行一个数字,方法名称采用filepath参数和long n参数,即生成的随机数的数量。 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. 我还将如何通过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. 因此,有人可以给我说明如何通过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 另外,为了从命令行运行程序,您需要做的就是在类中添加一个main方法,如下所示
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 这个主要假设您要从命令行传入2个参数,数字后跟文件名
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. filePath
是一个变量,用于保存文件的路径,因此您不想将其用双引号引起来。 If you do, it is treated as a String
, so the program searches for a file with path filePath
. 如果这样做,它将被视为String
,因此程序将使用路径filePath
搜索文件。
PrintWriter out = new PrintWriter(filePath); // no ""
The "tester" can run the program the same way you run it: java programName
“测试器”可以使用与运行程序相同的方式运行该程序: 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: 有两种测试方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.