在java中只接受一位数字

在java中只接受一位数字,java,Java,我正在写一个简单的程序,它接受多个输入,然后显示最大值和第二大值。我唯一的问题是我希望程序只接受个位数。我知道这是最基本的,但请容忍我。到目前为止,我编写的代码是: import javax.swing.JOptionPane; public class Largest { public static void main (String args[]) { /*Set variables and include a while function to for

我正在写一个简单的程序,它接受多个输入,然后显示最大值和第二大值。我唯一的问题是我希望程序只接受个位数。我知道这是最基本的,但请容忍我。到目前为止,我编写的代码是:

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 
import javax.swing.JOptionPane;
公务舱
{
公共静态void main(字符串参数[])
{
/*设置变量并包含while函数以强制程序执行
*在继续程序的其余部分之前,请输入10个数字*/
int计数器=0;
整数=0;
int最大=0;
int秒=0;
while(计数器<10)
{
//设置计数器
计数器++;
//输入整数,设置最大的数字作为第一个输出
number=Integer.parseInt(JOptionPane.showInputDialog(“输入整数”);
如果(数量>=最大){
最大=数量;
}else if(number>=second&&number
//设置计数器
计数器++;
while(true){
//输入整数,设置最大的数字作为第一个输出
number=Integer.parseInt(JOptionPane.showInputDialog(“输入整数”);
if(number<10&&number>-10)break;//如果是一位数字,则可以
JOptionPane.showMessageDialog(空,“仅输入一位数字”,
“数字太多”,JOptionPane。错误消息);
}

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

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

对于这种类型的问题,我个人会使用

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

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

公共类限制输入{
公共静态void main(字符串[]args){
新的限制输入();
}
公共限制输入(){
invokeLater(新的Runnable(){
@凌驾
公开募捐{
试一试{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}捕获(ClassNotFoundException ex){
}catch(实例化异常){
}捕获(非法访问例外){
}捕获(无支持的LookandFeelexception ex){
}
JTextField=新的JTextField(2);
field.setHorizontalAlignment(JTextField.RIGHT);
((AbstractDocument)field.getDocument()).setDocumentFilter(新的RestrictFilter());
JPanel panel=newjpanel(newgridbagloayout());
GridBagConstraints gbc=新的GridBagConstraints();
gbc.gridx=0;
gbc.gridy=0;
panel.add(新的JLabel(“请输入一个整数”)、gbc;
gbc.gridx++;
gbc.anchor=GridBagConstraints.WEST;
gbc.weightx=1;
面板。添加(字段,gbc);
int result=JOptionPane.showConfirmDialog(null,面板,“输入”,JOptionPane.OK\u取消选项,JOptionPane.QUESTION\u消息);
if(result==JOptionPane.OK\u选项){
System.out.println(“使用entered”+field.getText());
}
}
});
}
公共类RestrictFilter扩展了DocumentFilter{
public void insertString(DocumentFilter.FilterBypass fb,int offset,String text,AttributeSet attr)引发BadLocationException{
字符串currentText=fb.getDocument().getText(0,fb.getDocument().getLength());
if(currentText.startsWith(“-”)| | text.equals(“-”| | fb.getDocument().getLength()<1){
字符串值=文本。子字符串(0,1);
if(值等于(“-”){
if(currentText.startsWith(“-”){
超级。移除(fb,0,1);
}否则{
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)引发BadLocationException{
如果(长度>0){
fb.移除(偏移、长度);
}
插入字符串(fb、偏移量、字符串、属性);
}
}
}

签出,特别是实现文档过滤器的部分

您的意思是只希望他们能够实际输入一个数字(比如它不允许您输入两个字符),还是它应该只接受一个数字(比如如果超过9就会抛出错误)?刚刚意识到,如果输入,程序将始终显示第二高的数字为0。不确定为什么…它不应在任何输入中允许两位数。回到VB,我记得将变量设置为仅允许一位数,我相信,但这太长了ago@user1798926看看我的答案。你应该再问一次是否无效你也应该检查
number>=0
,或者用户可以输入几个数字的负值。谢谢,这与我刚才尝试的非常接近。我仍然有一个问题,就是总是出现零,我想我必须限制用户输入零谢谢你的链接,我还没有使用limiters@MadPr这就是我的意思-我确信JTextField有一个“显示宽度”和一个“最大输入长度”,但后来我意识到我把它和HTML表单混淆了!你的答案肯定更完整,并且强制使用数字字符。
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);
        }
    }
}