JTextfield数字验证?

huangapple go评论86阅读模式
英文:

JTextfield Validation for numbers?

问题

我正在尝试验证我的学号(输入为整数值)来自JTextField。我的代码编译成功,但在运行时出现NumberFormatException错误。以下是我的验证代码:

public int rno_vd() {
    int a=0,b=0,c=0,x=0,y=0;
    int vrno = Integer.parseInt(txtRno.getText());
    String r = String.valueOf(vrno);
    if (r.isEmpty()) {
        JOptionPane.showMessageDialog(null, "学号不能为空");
        a=1;
    }
    else if (Pattern.matches("[a-zA-Z]+", r)) {
        JOptionPane.showMessageDialog(null, "学号应为数字");
        b=1;
    }
    else if (vrno < 0) {
        JOptionPane.showMessageDialog(null, "学号不能为负数");
        c=1;
    }
    System.out.println(a + b + c);
    if (a==1 || b==1 || c==1) {
        x=1;
        return x;
    }
    else {
        y=0;
        return y;
    }
}

错误信息:

C:\Users\Hp\Desktop\jproject>javac -cp hibernatejar\*  *.java
注意: DBHandler.java 使用了未经检查或不安全的操作。
注意: 重新编译时使用 -Xlint:unchecked 以获取详细信息。

C:\Users\Hp\Desktop\jproject>java -cp hibernatejar\*;.  Sms
在线程 "AWT-EventQueue-0" 中的异常: java.lang.NumberFormatException: 输入字符串为空
        at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
        at java.base/java.lang.Integer.parseInt(Integer.java:662)
        at java.base/java.lang.Integer.parseInt(Integer.java:770)
        at AddFrame.lambda$new$1(AddFrame.java:80)
        at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967)
        at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308)
        at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
        at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
        at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
英文:

I am trying to validate my roll no (input of integer value) from JTextField. Well my code is compiling but while running it is giving me an error NumberFormatException.
Here is my validation code

public int rno_vd() {
	int a=0,b=0,c=0,x=0,y=0;
	int vrno =Integer.parseInt(txtRno.getText());
	String r = String.valueOf(vrno);
	if (r.isEmpty()) {
		JOptionPane.showMessageDialog(null,&quot;rno should not be empty&quot;);
		a=1;
    }
	else if (Pattern.matches(&quot;[a-zA-Z]+&quot;,r)) {
		JOptionPane.showMessageDialog(null,&quot;rno should be in digits&quot;);
		b=1;
    }
	else if (vrno &lt; 0) {
		JOptionPane.showMessageDialog(null,&quot;rno cannot be negative&quot;);
		c=1;
    }
	System.out.println(a + b + c);
	if (a==1 || b==1 || c==1) {
		x=1;
		return x;
    }
	else {
		y=0;
		return y;
	}
}

error

C:\Users\Hp\Desktop\jproject&gt;javac -cp hibernatejar\*  *.java
Note: DBHandler.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

C:\Users\Hp\Desktop\jproject&gt;java -cp hibernatejar\*;.  Sms
Exception in thread &quot;AWT-EventQueue-0&quot; java.lang.NumberFormatException: For input string: &quot;&quot;
        at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
        at java.base/java.lang.Integer.parseInt(Integer.java:662)
        at java.base/java.lang.Integer.parseInt(Integer.java:770)
        at AddFrame.lambda$new$1(AddFrame.java:80)
        at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967)
        at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308)
        at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
        at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
        at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)

答案1

得分: 1

以下是您要翻译的内容:

当文本字段为空时,会出现“NumberFormatException”。

线程异常“AWT-EventQueue-0”中发生java.lang.NumberFormatException:输入字符串:“”。

请先尝试验证文本,然后解析字符串。

// 首先验证文本输入
String r = txtRno.getText();

if (r.isEmpty())
{JOptionPane.showMessageDialog(null,"rno不能为空");
a=1;}
else if (Pattern.matches("[a-zA-Z]+",r))
{JOptionPane.showMessageDialog(null,"rno应为数字");
b=1;}
else if (vrno < 0)
{JOptionPane.showMessageDialog(null,"rno不能为负");
c=1;}

// 如果验证成功,则转换为整数
int vrno = Integer.parseInt(txtRno.getText());

英文:

It is getting NumberFormatException, when text field has empty value.

Exception in thread &quot;AWT-EventQueue-0&quot; java.lang.NumberFormatException: For input string: &quot;&quot;

Could you please try to validate the text first, and then parse the string?

    // Validating text input first
    String r = txtRno.getText();

    if (r.isEmpty())
        {JOptionPane.showMessageDialog(null,&quot;rno should not be empty&quot;);
            a=1;}
    else if (Pattern.matches(&quot;[a-zA-Z]+&quot;,r))
        {JOptionPane.showMessageDialog(null,&quot;rno should be in digits&quot;);
            b=1;}
    else if (vrno &lt; 0)
        {JOptionPane.showMessageDialog(null,&quot;rno cannot be negative&quot;);
            c=1;}

    // Converting to int, if validation is successful
    int vrno =Integer.parseInt(txtRno.getText());

答案2

得分: 0

Komal,我看到你想要验证 JTextField 中的学号,它应该只包含整数,除了数字之外的任何字符都不应被接受...
我建议你尝试在每次按键释放时使用 KeyEvent 的 KeyListener 进行验证。
每次按键都会验证,如果是数字就没问题,如果不是,它会显示一个对话框,上面写着"只接受数字"。

我分享我的代码,希望能有所帮助:

//********检查值是否为数字的函数*********
public static boolean isNumeric(String str) { 
    try {  
        Integer.parseInt(str);  
        return true;
    } 
    catch(NumberFormatException e){  
        return false;  
    }  
}
//************************函数结束******************************


//txtRno 是我的 JTextField 

txtRno.addKeyListener(new KeyListener(){
    public void keyPressed(KeyEvent e)
    {
        //代码  	
    }
    public void keyReleased(KeyEvent e)
    {
        String value = txtRno.getText();
        int l = value.length();
        if(!isNumeric(value) && l>0){//如果不是数字,它将不允许您编辑 JTextField 并显示错误消息
            txtRno.setEditable(true);
            JOptionPane.showMessageDialog(c,"您需要输入数字","错误",JOptionPane.ERROR_MESSAGE);
            txtRno.requestFocus();
            txtRno.setText("");
            txtRno.setEditable(true);
            lblError.setText("");
        } 
        else { //否则它将接受输入,因为它已经是数字或整数
            txtRno.setEditable(true);
            lblError.setText("");
        }
    }
    public void keyTyped(KeyEvent e)
    {
        //代码
    }
});
英文:

Komal here as I can see you want to validate JTextField for roll numbers ie should only contain integers, any other character instead of numbers should not be accepted...
Well, I suggest you to try validating on every keyReleased using KeyListener of KeyEvent.
Every key you press is validated if its number its good to go if its not it will show Dialog box saying "only numbers accepted".

I am sharing my code I hope it might help

//********function to check if value is numric or not*********
public static boolean isNumeric(String str) { 
  		try {  
    		Integer.parseInt(str);  
    		return true;
  		} 
  		catch(NumberFormatException e){  
    		return false;  
  		}  
	}
//************************function ends******************************


//txtRno is my JTextField 

txtRno.addKeyListener(new KeyListener(){
		public void keyPressed(KeyEvent e)
		{
  			//code  	
		}
		public void keyReleased(KeyEvent e)
		{
  			String value = txtRno.getText();
    		int l = value.length();
    		if(!isNumeric(value) &amp;&amp; l&gt;0){//if not numric it will not allow you to edit JTextField and show error message
    			txtRno.setEditable(true);
        		JOptionPane.showMessageDialog(c,&quot;You need to enter number&quot;,&quot;ERROR&quot;,JOptionPane.ERROR_MESSAGE);
        		txtRno.requestFocus();
        		txtRno.setText(&quot;&quot;);
       			txtRno.setEditable(true);
        		lblError.setText(&quot;&quot;);
    		} 
    		else { //else it will take the input as it already number or integer 
        		txtRno.setEditable(true);
        		lblError.setText(&quot;&quot;);
    		}
		}
		public void keyTyped(KeyEvent e)
		{
  			//code
		}
	});

huangapple
  • 本文由 发表于 2020年7月30日 13:56:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63167002.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定