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 :(得分: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 :(得分: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);
}
答案 2 :(得分: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);
}
}