2015-02-10 65 views
0

我有一個任務來編寫一個應用程序,該應用程序將接受來自用戶的輸入,並將每個答案存儲在一個字符串數組中。此應用程序還必須檢查用戶輸入的空值,並重新提示用戶輸入其答案。應用程序必須只重複空白的問題,因爲這個應用程序有50個問題。循環檢查用戶輸入的空白​​空間

這是到目前爲止我的代碼:

for(iLoop=0; iLoop<noOfQuest; iLoop++) 
     { 
      if(noOfEmails<1) 
      { 
       System.out.println("FILE_ERROR: Please ensure line \"noOfEmails\" is more than 0"); 
      } 
      if(noOfQuest==1) 
      { 
       System.out.println(prefinalMess); 
       System.out.println(questionArr[0]); 
       ansArray[iLoop]=ans.next(); 
       System.out.println(finalMess); 
      } 
      if(noOfQuest==2) 
      { 
       System.out.println(questionArr[0]); 
       ansArray[iLoop]=ans.next(); 
       System.out.println(prefinalMess); 
       System.out.println(questionArr[1]); 
       ansArray[iLoop]=ans.next(); 
       System.out.println(finalMess); 
      } 
      if(noOfQuest==3) 
      { 
       System.out.println(questionArr[0]); 
       ansArray[iLoop]=ans.next(); 
       System.out.println(questionArr[1]); 
       ansArray[iLoop]=ans.next(); 
       System.out.println(prefinalMess); 
       System.out.println(questionArr[2]); 
       ansArray[iLoop]=ans.next(); 
       System.out.println(finalMess); 
      } 
      if(noOfQuest==4) 
      { 
       System.out.println(questionArr[0]); 
       ansArray[iLoop]=ans.next(); 
       System.out.println(questionArr[1]); 
       ansArray[iLoop]=ans.next(); 
       System.out.println(questionArr[2]); 
       ansArray[iLoop]=ans.next(); 
       System.out.println(prefinalMess); 
       System.out.println(questionArr[3]); 
       ansArray[iLoop]=ans.next(); 
       System.out.println(finalMess); 
      } 
      if(noOfQuest==5) 
      { 
       System.out.println(questionArr[0]); 
       ansArray[iLoop]=ans.next(); 
       System.out.println(questionArr[1]); 
       ansArray[iLoop]=ans.next(); 
       System.out.println(questionArr[2]); 
       ansArray[iLoop]=ans.next(); 
       System.out.println(questionArr[3]); 
       ansArray[iLoop]=ans.next(); 
       System.out.println(prefinalMess); 
       System.out.println(questionArr[3]); 
       ansArray[iLoop]=ans.next(); 
       System.out.println(finalMess); 
      } 
     } 

我還必須開發新方法來檢查每個答案的輸入。

回答

0

這一點的方法來讀取並通過命令行來檢查用戶輸入:

public static List<String> readNLinesOfInput(int lines2Read){ 
    List<String> inputs = new ArrayList<String>(); 
    try (Scanner sc = new Scanner(System.in)) { 
     while(inputs.size() < lines2Read) { 
      System.out.println("Enter the "+(inputs.size()+1)+" line: "); 
      String line = sc.nextLine(); 
      if("".equals(line)){ 
       System.out.print("Empty lines a not allowed. "); 
       continue; 
      } 
      inputs.add(line); 
     } 
    } 
    return inputs; 
} 

你可以把它和每一行,像這樣遍歷:

public static void main(String[] args) { 
    List<String> list = readNLinesOfInput(50); 
    for(String line: list){ 
     System.out.println(line); 
    } 
} 
+0

非常感謝,讓我當涉及到添加更多問題時,工作更容易:3 – 2015-02-10 14:50:02