我会使用do while循环吗?

时间:2012-03-28 22:37:13

标签: java

我希望用户能够搜索此短名单,但如果输入的号码错误,我不希望JOptionPane关闭。另外我如何设置终止词,即如果用户输入“退出”,循环将结束,程序将退出。我会使用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;

2 个答案:

答案 0 :(得分: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;

    }
}

这不是完美的代码,但它应该完成这项工作。如果您有任何疑问,我将非常乐意为您提供帮助。

快乐编码,

海登

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