2013-12-14 46 views
2

我試圖做一個ArrayList,需要用戶輸入多個名稱,直到插入單詞done,但我不太確定怎麼樣。如何實現這一目標?我必須做一個循環,用戶輸入,直到「完成」輸入

+0

你使用任何特定的編程語言?無論如何,至少會發布一些你的嘗試代碼,否則這個問題會因缺乏努力而關閉。 – nos

+0

其java對不起忘了添加 – yoyo

+0

您是否期望在列表中插入「完成」?你已經做了什麼代碼來激發這個問題的解決方案? – Makoto

回答

-2
ArrayList<String> names = new ArrayList<String>(); 
String userInput; 
Scanner scanner = new Scanner(System.in); 
while (true) { 
    userInput = scanner.next(); 
    if (userInput.equals("done")) { 
     break; 
    } else { 
     names.add(userInput); 
    } 
}  
scanner.close(); 
+0

爲什麼downvote?有用。 – zbr

+5

因爲使用中斷而不是循環條件很難閱讀。 while(!userInput.equals(「done」))在閱讀代碼時更有意義 –

+0

現在代碼的可讀性略差,現在有足夠的理由在這裏進行downvote? – zbr

-1
String[] inputArray = new String[0]; 
do{ 
    String input=getinput();//replace with custom input code 
    newInputArray=new String[inputArray.length+1]; 
    for(int i=0; i<inputArray.length; i++){ 
    newInputArray[i]=inputArray[i]; 
    } 
    newInputArray[inputArray.length]=input 
    intputArray=newInputArray; 
}while(!input.equals("done")); 

未經測試的代碼,把它與一粒鹽。

+0

好,向那些試圖幫助你的人投票。 – Kent

+0

哦,那不是他。他還不能倒下。 – zbr

+0

哎呀,抱歉的責備,我是新的:) – Kent

0

我可能會做它像這樣 -

public static void main(String[] args) { 
    System.out.println("Please enter names seperated by newline, or done to stop"); 
    Scanner scanner = new Scanner(System.in);  // Use a Scanner. 
    List<String> al = new ArrayList<String>(); // The list of names (String(s)). 
    String word;         // The current line. 
    while (scanner.hasNextLine()) {    // make sure there is a line. 
    word = scanner.nextLine();     // get the line. 
    if (word != null) {       // make sure it isn't null. 
     word = word.trim();      // trim it. 
     if (word.equalsIgnoreCase("done")) {  // check for done. 
     break;         // End on "done". 
     } 
     al.add(word);        // Add the line to the list. 
    } else { 
     break;         // End on null. 
    } 
    } 
    System.out.println("The list contains - "); // Print the list. 
    for (String str : al) {      // line 
    System.out.println(str);     // by line. 
    } 
} 
1
ArrayList<String> list = new ArrayList<String>(); 
    String input = null; 
    while (!"done".equals(input)) { 
     // prompt the user to enter an input 
     System.out.print("Enter input: "); 

     // open up standard input 
     BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 


     // read the input from the command-line; need to use try/catch with the 
     // readLine() method 
     try { 
      input = br.readLine(); 
     } catch (IOException ioe) { 
      System.out.println("IO error trying to read input!"); 
      System.exit(1); 
     } 
     if (!"done".equals(input) && !"".equals(input)) 
      list.add(input); 
    } 
    System.out.println("list = " + list); 
+0

雖然正確,但input.equals(「done」)或使用變量來保存break字符串通常是首選。我是否也可以建議將兩者都轉換爲大寫,以避免大小寫敏感問題? (編輯:實際上,我剛剛做了改變......) –

相關問題