2017-02-21 53 views
0

我是新來的編程,最近試圖做一個簡單的程序來創建多個名稱與我想要的目錄。它正在工作,但在一開始,它不加問我就加入第一個「數字」。之後,我可以製作儘可能多的文件夾。如何創建多個目錄?

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.

如果這是一個愚蠢的問題,我將立即刪除它。先謝謝你。

+0

我最好的猜測是你的IDE添加了這些。如果通過命令行運行程序,會發生這種情況嗎? –

+0

另外,考慮使用'for'循環而不是'while'循環。 – ahjohnston25

+0

@ ahjohnston25不,for循環會改變行爲,由於錯誤處理。 –

回答

3

這是因爲你的sc.nextInt()在這一行:

int number_of_folders = sc.nextInt(); 

不消耗最後一個換行符。

當您輸入您按下的目錄數量輸入,它也有它的ASCII值(10)。當你閱讀nextInt時,換行符還沒有被讀取,nextLine()首先收集該行,然後繼續正常地處理下一個輸入。

0

在這種情況下,你可以使用File類的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(); 
} 

應該清楚如何融入你的代碼這一點。