2017-02-11 24 views
-2

我的程序要求用戶輸入他們在工作目錄(包含文本)中的文件名,然後輸入也在同一目錄中的輸出文件名。之後,用戶必須選擇是否要大寫或小寫文件中的所有文本。我如何重新使用這段代碼?

一旦他們選擇了應該給他們處理另一個文件的選項。這是我遇到麻煩的地方。打印完成後「您想處理另一個文件嗎?Y是或N是否?」我如何讓它回到起點?

現在我的代碼保持循環回「大寫或小寫都寫着」我需要它停止這樣做,並詢問用戶是否要處理另一個文件時,如果有需要回去,並要求輸入並再次輸出文件名稱。

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 
    System.out.println("Please enter the input data file name:"); 
    String fileInput = sc.next(); 
    System.out.println("Please enter the output data file name:"); 
    String fileOutput = sc.next(); 
    while(true){ 
     System.out.println("A: Capitalize all words.\nB: Lowercase all words."); 

     System.out.println("enter choice:"); 
     char choice = sc.next().charAt(0); 
     if(choice == 'A'){ 
      capitalize(fileInput, fileOutput); 
     }else{ 
      lowercase(fileInput, fileOutput); 
     } 

    } 
    System.out.println("Process another file? Y for Yes or N for No"); 
} 

回答

1

你只需要包裝所有的代碼在while循環,如下: while循環只有重複的代碼吧:

public static void main(String[] args) { 
    while (true) { 
     Scanner sc = new Scanner(System.in); 
     System.out.println("Please enter the input data file name:"); 
     String fileInput = sc.next(); 
     System.out.println("Please enter the output data file name:"); 
     String fileOutput = sc.next(); 
     System.out.println("A: Capitalize all words.\nB: Lowercase all words."); 

     System.out.println("enter choice:"); 
     char choice = sc.next().charAt(0); 
     if (choice == 'A') { 
      capitalize(fileInput, fileOutput); 
     } else { 
      lowercase(fileInput, fileOutput); 
     } 

     System.out.println("Process another file? Y for Yes or N for No"); 
     String processAnother = sc.next(); 
     if (processAnother.equals("N") || processAnother.equals("n")) break; 
    } 
} 
+0

是的,我有種想我將不得不把所有的代碼爲while循環,我只是不知道我會添加一個新的字符串處理另一個。謝謝! – user3496266