[英]Using a for-loop and PrintWriter, how do I create multiple randomly named files each that have a set of their own code in them?
基本上问题是在编译运行并输入输入之后。 仅创建一个文件。 一切正常,除了当我输入一个大于一的数字时。 输入大于 1 的数字应该允许我拥有多个文件,每个文件都根据我的理解生成随机名称,对吧? 相反,它选择只创建一个具有随机名称的文件并正常执行所有操作,除了创建我告诉它的那几个额外文件。
这是为了个人娱乐,我使用记事本++来创建它,然后我在命令提示符下使用 javac 和 java 编译和运行它。 我基本上是在使用我们几天前在 class 中学到的东西来创建这个,还有很多我必须研究的额外东西,但我真的很想知道如何做到这一点并且找不到太多关于这样做的内容一个for循环,这就是我想要的方式。
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
public class rangen {
static String getnumlet(int n) {
String numlet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqr" +
"stuvwxyz0123456789";
StringBuilder sb = new StringBuilder(n);
for (int i = 0 ; i < n ; i++) {
int index = (int)(numlet.length() * Math.random());
sb.append(numlet.charAt(index));
}
return sb.toString();
}
public static void main(String[] args) {
final int length = 10;
int amount = 0;
String printername = (rangen.getnumlet(length) + ".java");
String name = (printername.substring(0 ,
printername.indexOf('.')).trim());
Scanner input = new Scanner(System.in);
PrintWriter tofile = null;
System.out.print("Enter the amount of files you want to create: ");
amount = input.nextInt();
for (int i = 1 ; i <= amount ; i++) {
try {
tofile = new PrintWriter(printername);
tofile.print("// Creator: Unknown...\n");
tofile.print("// Date Created: 9-28-2019\n");
tofile.print("// Last Modified: 9-28-2019\n");
tofile.print("// Description: This file was \n" +
"// randomly generated.\n");
tofile.print("public class " + name + " {\n");
tofile.print(" public static void main(String[] args) {\n");
tofile.print(" private static final double inf = \n" +
" Double.POSITIVE_INFINITY;\n");
tofile.print(" for (int i = 1 ; i <= inf ; i++) {\n");
tofile.print(" System.out.print(\"yeet \" + i);\n");
tofile.print(" }\n");
tofile.print(" }\n");
tofile.print("}\n");
for (int x = 0 ; x <= 5; x++ ) {
tofile.print("// LOL " + x + "\n");
}
}
catch (FileNotFoundException e) {
System.out.println("couldn't create " + printername);
}
tofile.close();
}
}
}
假设您在控制台中输入了 3 的值。 然后我希望它创建三个单独的文件,每个文件中都有我告诉它写入文件的代码。 不会出现错误消息,但只为我制作了一个文件而不是 3 个。
您需要在for
循环的每次迭代中生成一个新的随机文件名。 如所写,您的程序会生成一个随机文件名,并在每次迭代时使用相同的名称。
for (int i = 1 ; i <= amount ; i++) {
String printername = (rangen.getnumlet(length) + ".java");
String name = printername.substring(0, printername.indexOf('.')).trim();
try {
tofile = new PrintWriter(printername);
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.