2012-03-28 66 views
1

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

請把大括號('{}')在你的if-else語句,只是爲了保存自己的頭痛。 – 2012-03-28 22:52:22

+0

謝謝你們,我得到它的工作! – 2012-03-28 23:05:39

回答

1

相信do while循環非常適合這些這樣的菜單-IO循環,因爲你需要至少一個IO。通用僞代碼:

Var command; 
do { 
    command = input(); 
    switch(command){ 
    case opt1 : 
     // do something 
    case opt2 : 
     // do something 
    case default : 
     // unexpected command 
    } 
} while(command != "quit"); 
+0

Psuedo代碼沒問題,Java會更好。如果OP嘗試進行天真的轉換,那麼這段代碼有一些缺陷。 – 2012-03-28 22:53:54

2

你可以嘗試這樣的事:

import javax.swing.JOptionPane; 


public class Key { 

    public static void main(String[] args){ 

     int key, list[] = {8,22,17,24,15}; 
     int index; 

     String userOption = "null"; 

     while(!userOption.equals("quit")){ 
      userOption = JOptionPane.showInputDialog(null,"Input the integer to find"); 

      //Take the cancel action into account 
      if(userOption == null){ 
       break; 
      } 

      //Try to get valid user input 
      try{ 
       key = Integer.parseInt(userOption); 

       index = searchList(list, key); 

       if(index < list.length){ 
        JOptionPane.showMessageDialog(null,"The key " + key + " found the element " + index); 
        //uncommented the break below to exit from the loop if successful 
        //break; 
       } 
       else 
        JOptionPane.showMessageDialog(null,"The key " + key + " not found"); 

      } catch (Exception e){ 
       //Throw an exception if anything but an integer or quit is entered 
       JOptionPane.showMessageDialog(null,"Could not parse int", "Error",JOptionPane.ERROR_MESSAGE); 
      } 
     } 
     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; 

    } 
} 

這是不完美的代碼,但它應該做的工作。如果您有任何疑問,我會很樂意提供幫助。

編碼快樂,

海登