简体   繁体   中英

How to create multiple directories?

I am new to programming and recently have tried to make a simple program to create multiple directories with names as I want. It is working but at the beginning, it is adding first "number" without asking me. After this, I can make as many folders as I want.

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);
}
}

If I chose to make 5 folders, something like this is happening:

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.

If it is a stupid question, I will remove it immediately. Thank you in advance.

It's because your sc.nextInt() in this line :

int number_of_folders = sc.nextInt();

doesn't consume last newline character.

When you inputted number of directories you pressed enter, which also has it's ASCII value (10). When you read nextInt, newline character haven't been read yet, and nextLine() collect that line first, and than continue normally with your next input.

In this case, you can just use the mkdir part of the File class as so:

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();
}

It should be clear how to incorporate this into your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM