在java中只接受一个数字 [英] accept only a single digit in java

查看:84
本文介绍了在java中只接受一个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  import javax.swing.JOptionPane; 

公共类最大
{
public static void main(String args [])
{
/ *设置变量并包含一个while函数来强制程序在进入程序的其余部分之前需要花费
*十个数字。 * /
int counter = 0;
int number = 0;
int maximum = 0;
int second = 0;

while(counter< 10)
{
//设置计数器
counter ++;
//输入整数,设置最大数字作为第一个输出
number = Integer.parseInt(JOptionPane.showInputDialog(Enter integer));
if(number> = max){
maximum = number;
}否则if(number> = second&& number< = maximum){
//设置第二大整数作为输出
second = number;
}
}

//显示最大数字,后跟第二大数字
System.out.println(最大数字输入:+最大) ;
System.out.println(第二大输入:+秒);

System.exit(0); //终止应用程序
} //结束方法主
} //结束类


解决方案

对于这类问题,我个人会使用和文本组件功能,特别是实现文档过滤器的部分


I am writing a simple program that takes multiple inputs and displays the largest then second largest. My only problem is that I want the program to accept only single digits. I know this goes back to basics, but bear with me. The code I have written so far is:

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 

解决方案

For this type of problem, personally, I would use a DocumentFilter

It allows you to restrict the type of characters coming into the field as well as the number of characters.

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);
        }
    }
}

Check out MDP's Weblog and Text Component Features, in particular the section of Implementing a Document Filter

这篇关于在java中只接受一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆