java - 我会只使用 do while 循环吗?

标签 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;

最佳答案

你可以尝试这样的事情:

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;

    }
}

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

快乐编码,

海登

关于java - 我会只使用 do while 循环吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9916677/

相关文章:

java - 使用 Mockito 为 Java 8 lambda 表达式编写 stub

java - Java的SASS实现?

Java Swing : Read many images files without memory problems?

java - 在多个字符上拆分字符串

java - 有没有更好的方法可以使用 Stream 进行编写?

java - 在 Eclipse 和 Maven 中使用 JUnit 的类路径问题

java - 使用枚举类型重载

java - 迭代 Collection,避免在循环中删除对象时出现 ConcurrentModificationException

java - BigDecimal ("0") 和 BigDecimal.ZERO 之间有区别吗?

java - 多个 Actor 作为按钮 - 检测哪个 Actor 被触摸/点击