2015-07-11 77 views
0
public static void main(String[] args) { 

     ArrayList<String> names = new ArrayList<String>(); 

     names.add(JOptionPane.showInputDialog("Enter type of pie")); 

    } 

我該如何循環這條語句?我試過dowhile (!names.equalsIgnoreCase("q"));,但找不到它。如何在數組列表中循環添加語句

 names.add(JOptionPane.showInputDialog("Enter type of pie")); 
+0

你是什麼意思它無法找到它呢? – Marcin

+0

編譯錯誤說找不到符號「名稱」 – dan

+0

在添加for循環之前它工作嗎? I.e是否在上面發佈的代碼編譯? – Marcin

回答

1

這工作正常。

 String str = null; 
    List<String> names = new ArrayList<String>(); 
    do 
    { 
     str = JOptionPane.showInputDialog("Enter type of pie"); 
    if(!str.equalsIgnoreCase("q")) 
     names.add(str); 
    }while(!str.equalsIgnoreCase("q")); 
+1

因此,向列表中添加「q」可以嗎? – Shar1er80

+0

你可以把它變成一個'while'循環,並避免將'q'加入到'List'中 - 這相當難看。 –

0

在你的循環,你應該通過名稱列表迭代和每個元素調用equalsIgnoreCase(「Q」),將另一個輸入對話框每次迭代。

考慮:

while (names.isEmpty() || !names.get(names.size() - 1).equalsIgnoreCase("q")) 
{ 
    names.add(JOptionPane.showInputDialog("Enter type of pie")); 
} 

如果你想忽略餡餅「Q」的名字:

while (names.isEmpty() || !names.get(names.size() - 1).equalsIgnoreCase("q")) 
{ 
    names.add(JOptionPane.showInputDialog("Enter type of pie")); 
} 
// populates the ArrayList names with the JOptionPane user input 
if (!names.isEmpty()) 
{ 
    names.remove(names.size() - 1); 
    // remove the last name inputted by the user 
    // since the only way to terminate the loop is by entering "q", 
    // you are removing the name of "q" from the list. 
} 

編輯: 這是一個更好的實現,因爲它只是增加了名稱不是「q」:

String userInput = new String(); 
while (!userInput.equalsIgnoreCase("q")) 
{ 
    userInput = JOptionPane.showInputDialog("Enter type of pie"); 
    if (!userInput.equalsIgnoreCase("q")) 
    { 
     names.add(userInput); 
    } 
} 
1

嘗試......

public static void main(String[] args) throws Exception { 
    List<String> names = new ArrayList(); 
    String input = ""; 
    while (!input.equalsIgnoreCase("q")) { 
     input = JOptionPane.showInputDialog("Enter type of pie"); 
     if (!input.equalsIgnoreCase("q")) { 
      names.add(input); 
     } 
    } 

    System.out.println(names); 
}