我希望用戶能夠搜索這個簡短的列表,但我不希望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