3

我正在编写一个简单的程序,它接受多个输入并显示最大的然后是第二大的。我唯一的问题是我希望程序只接受个位数。我知道这可以追溯到基础,但请耐心等待。到目前为止我写的代码是:

import javax.swing.JOptionPane;

public class Largest 
{
    public static void main (String args[]) 
    {
        /*Set variables and include a while function to force the program to take
        * ten numbers before proceeding to the rest of the program. */
        int counter = 0;
        int number = 0;
        int largest = 0;
        int second = 0;

        while (counter < 10)
        {
            // Set the counter
            counter++;
            //Input integer, set the largest number as the first output
            number = Integer.parseInt(JOptionPane.showInputDialog("Enter integer"));
            if (number >= largest) {
                largest=number;
            } else if (number >= second && number <= largest) {
                // Set the second largest integer as the output
                second=number;
            }
        }

        //Display the largest number, followed by the second largest number
        System.out.println("Largest number input: " + largest);
        System.out.println("Second largest input: " + second); 

        System.exit(0);             //terminate the application
    }                   //end method main
}                       //end class 
4

3 回答 3

3

对于这类问题,就个人而言,我会使用DocumentFilter

它允许您限制进入字段的字符类型以及字符数。

在此处输入图像描述

public class RestrictInput {

    public static void main(String[] args) {
        new RestrictInput();
    }

    public RestrictInput() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JTextField field = new JTextField(2);
                field.setHorizontalAlignment(JTextField.RIGHT);
                ((AbstractDocument) field.getDocument()).setDocumentFilter(new RestrictFilter());
                JPanel panel = new JPanel(new GridBagLayout());
                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridx = 0;
                gbc.gridy = 0;
                panel.add(new JLabel("Please enter a integer:"), gbc);
                gbc.gridx++;
                gbc.anchor = GridBagConstraints.WEST;
                gbc.weightx = 1;
                panel.add(field, gbc);

                int result = JOptionPane.showConfirmDialog(null, panel, "Input", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
                if (result == JOptionPane.OK_OPTION) {
                    System.out.println("Use entered " + field.getText());
                }

            }
        });
    }

    public class RestrictFilter extends DocumentFilter {

        public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
            String currentText = fb.getDocument().getText(0, fb.getDocument().getLength());
            if (currentText.startsWith("-") || text.equals("-") || fb.getDocument().getLength() < 1) {
                String value = text.substring(0, 1);
                if (value.equals("-")) {
                    if (currentText.startsWith("-")) {
                        super.remove(fb, 0, 1);
                    } else {
                        super.insertString(fb, 0, value, attr);
                    }
                } else if (fb.getDocument().getLength() < 2 && (value.equals("-") || Character.isDigit(value.charAt(0)))) {
                    super.insertString(fb, offset, value, attr);
                }
            }
        }

        public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String string, AttributeSet attr) throws BadLocationException {
            if (length > 0) {
                fb.remove(offset, length);
            }
            insertString(fb, offset, string, attr);
        }
    }
}

查看MDP 的 WeblogText Component Features,尤其是实现文档过滤器部分

于 2012-11-05T00:47:49.967 回答
2
//Set the counter
counter++;
while (true) {
    //Input integer, set the largest number as the first output
    number = Integer.parseInt(JOptionPane.showInputDialog("Enter integer"));
    if (number < 10 && number > -10) break; //If it's one digit, it's OK
    JOptionPane.showMessageDialog(null, "Enter only one digit",
        "Too many digits", JOptionPane.ERROR_MESSAGE);
}

这样做是启动一个无限循环。如果数字只有一位,它将结束循环并继续。否则,它将再次从循环的开头开始并要求一个有效的数字。

于 2012-11-05T00:29:36.573 回答
1

只需使用自定义 JOptionDialog ,您将 JTextField 限制为 1 个字符宽度。

于 2012-11-05T00:30:55.810 回答