2012-03-28 49 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; 

    } 
} 

这是不完美的代码,但它应该做的工作。如果您有任何疑问,我会很乐意提供帮助。

编码快乐,

海登