我正在尝试将随机数写入文件。因此,基本上每行一个数字,方法名称采用filepath参数和long n参数,即生成的随机数的数量。这是我到目前为止的内容:
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();
}
我在正确的轨道上吗?另外,我将如何通过cmd运行该程序。我知道用于编译和运行它的命令,但是我认为我需要一个测试器来运行它。因此,有人可以给我说明如何通过cmd运行此代码的方法。
编辑:正常工作!谢谢大家的帮助!
您可以轻松打印。而不是做
out.write(num + "\n");
你反而想做
out.println(num);
这是跨平台的(在我看来,它更易于阅读)。
此外,为了从命令行运行程序,您所需要做的就是在类中添加一个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);
}
这个主要假设您要从命令行传入2个参数,数字后跟文件名
希望这对您有所帮助
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句