在java中只接受一个数字

时间:2012-11-05 00:26:01

标签: java

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

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 

3 个答案:

答案 0 :(得分:3)

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

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

enter image description here

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's WeblogText Component Features,特别是实施文档过滤器

部分

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

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

答案 2 :(得分:1)

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