如何验证输入的文本是否为数字? [英] How to validate if Text entered is a numeric number?
问题描述
我有一个计算应用程序,我需要验证字段以检查输入的值是否为数字而不是字母数字。我对这些代码有一些想法。
请指导我,如果我做错了什么或看起来像菜鸟,因为这是我第一次尝试Swing。
I have a calculation application which I need to validate the fields to check if the values entered are numeric numbers and not alphanumeric. I have some ideas about the codes.
Please guide me if I have done anything wrong or seem noob as this is my first time trying out Swing.
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
String text1 = jTextField1.getText(); // TODO add your handling code here:
}
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
String text2 = jTextField2.getText(); // TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (text1 and text2 != <numeric number>){
JOptionPane.showConfirmDialog(null, "Please enter numbers only", "naughty", JOptionPane.CANCEL_OPTION);
}
// First we define float variables.
float num1, num2, result;
// We have to parse the text to a type float.
num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());
// Now we can perform the addition.
result = num1+num2;
// We will now pass the value of result to jTextField3.
// At the same time, we are going to
// change the value of result from a float to a string.
jTextField3.setText(String.valueOf(result));
// TODO add your handling code here:
}
请做帮助。那么为什么我的NetBeans一直告诉我它不能识别JOptionPane命令?
Please do help. By the way why does my NetBeans keep informing me that it does not recognize the "JOptionPane" Command?
推荐答案
Float.parseFloat()
将抛出 NumberFormatException
如果 String
不是数字且无法解析为 Float
。您可以添加 try-catch
块来检查这种情况:
Float.parseFloat()
will throw a NumberFormatException
if the String
isn't numeric and cannot be parsed into a Float
. You can add a try-catch
block to check for this condition:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
float num1, num2, result;
try {
num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());
result = num1+num2;
jTextField3.setText(String.valueOf(result));
} catch (NumberFormatException e) {
JOptionPane.showConfirmDialog(null, "Please enter numbers only", "naughty", JOptionPane.CANCEL_OPTION);
}
}
这篇关于如何验证输入的文本是否为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!