我正在创建一个项目,当用户想要添加客户时,会生成随机的“UserID”。与此UserID一起,使用格式化的userID创建文件,该用户ID包含用户输入的名字和姓氏。我目前正在使用随机生成用户ID,并创建了一个do while循环以避免可能的重复。在最终的项目中,我将随机设置从9999拉出,但是为了演示和重复测试目的,它被设置为1。
突然间,我的do-while循环无法正常运行。我试过移动一些东西,检查语法和更改目录,但没有任何工作。
为什么我的do-while循环用作反复制文件方法不起作用?
public static void userAddition() throws IOException
{
boolean retry = true;
String formattedUserId = "";
Random randomNumbers = new Random();
int userId;
final int MAX_RETRIES = 10;
int retryCount = 0;
do
{
retryCount++;
userId = randomNumbers.nextInt(1);
formattedUserId = String.format("%04d", userId);
File f = new File("C:/Users/Nick/Desktop/Library" + formattedUserId + ".txt");
retry = f.exists();
}
while (retry && retryCount < MAX_RETRIES);
if (retry)
{
System.out.println("Error");
}
else
{
// happy path
String userFirstName = JOptionPane.showInputDialog("Enter the customer's first name:");
String userLastName = JOptionPane.showInputDialog("Enter the customer's last name:");
FileWriter fw = new FileWriter(formattedUserId + ".txt", true);
PrintWriter outputFile = new PrintWriter(fw);
outputFile.printf("#%s%n", formattedUserId);
outputFile.printf("%s %s", userFirstName, userLastName);
System.out.println(formattedUserId);
outputFile.close();
}
}
}
我希望do-while循环在达到MAX_RETRIES并显示“Error”之前运行10次。
你测试文件C:/Users/Nick/Desktop/Library0000.txt
的存在:
File f = new File("C:/Users/Nick/Desktop/Library" + formattedUserId + ".txt");
然后在项目的文件夹中创建名为0000.txt
的文件:
FileWriter fw = new FileWriter(formattedUserId + ".txt", true);
所以你的存在测试永远不会真实:)
简单的解决方法是将计算的文件名存储在变量中:
String fileName = String.format("C:/Users/Nick/Desktop/Library/%04d.txt", userId);
File f = new File(fileName);
...
FileWriter fw = new FileWriter(fileName, true);
顺便说一句,看看try-with-resources,你应该像这样使用它:
try (Writer writer = new PrintWriter(FileWriter(fileName, true))) {
writer.printf("#%s%n", formattedUserId);
writer.printf("%s %s", userFirstName, userLastName);
// notice: no close(), this is handled automatically and better!
}