如何创建多个目录?

How to create multiple directories?

我是编程新手,最近尝试制作一个简单的程序来创建多个目录,并根据需要命名。它正在工作,但在开始时,它在没有询问我的情况下先添加 "number" 。在此之后,我可以制作任意数量的文件夹。

public class Main {
public static void main(String args[]) throws IOException{
    Scanner sc = new Scanner(System.in);
    System.out.println("How many folders do you want?: ");
    int number_of_folders = sc.nextInt();
    String folderName = "";
    int i = 1;
    do {
        System.out.println("Folder nr. "+ i);
        folderName = sc.nextLine();
        try {
            Files.createDirectories(Paths.get("C:/new/"+folderName));
            i++;
        }catch(FileAlreadyExistsException e){
            System.err.println("Folder already exists");
        }
    }while(number_of_folders > i);
}
}

如果我选择制作 5 个文件夹,就会发生这样的事情:

1. How many folders do you want?: 
2. 5
3. Folder nr. 0
4. Folder nr. 1
5. //And only now I can name first folder nad it will be created.

如果是愚蠢的问题,我会立即将其删除。提前谢谢你。

在这种情况下,您可以只使用 File class 的 mkdir 部分:

String directoryName = sc.nextLine();
File newDir = new File("/file/root/"+directoryName);
if (!newDir.exists()) { //Don't try to make directories that already exist
    newDir.mkdir();
}

应该清楚如何将其合并到您的代码中。

这是因为你的sc.nextInt()在这一行:

int number_of_folders = sc.nextInt();

不消耗最后一个换行符。

当您输入目录数时按下回车键,它也有它的 ASCII 值 (10)。当您读取 nextInt 时,换行符尚未被读取,nextLine() 首先收集该行,然后正常继续您的下一个输入。