Search code examples
javacreate-directory

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.


Solution

  • 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.