我希望用户能够搜索这个简短的列表,但我不希望JOptionPane关闭,如果输入了错误的号码。另外我将如何设置一个终止字,即如果用户键入“退出”循环将结束,程序将退出。我会用while while循环吗?我只使用do while循环吗?
int key, list[] = {8,22,17,24,15};
int index;
key = Integer.parseInt(JOptionPane.showInputDialog(null,"Input the integer to find"));
index = searchList(list, key);
if(index < list.length)
JOptionPane.showMessageDialog(null,"The key " + key + " found the element " + index);
else
JOptionPane.showMessageDialog(null,"The key " + key + " not found");
System.exit(0);
}
private static int searchList(int[] n, int k) {
int i;
for (i = 0; i < n.length; i++)
if(n[i] == k)
break; //break loop if key found
return i;
请把大括号('{}')在你的if-else语句,只是为了保存自己的头痛。 – 2012-03-28 22:52:22
谢谢你们,我得到它的工作! – 2012-03-28 23:05:39