[英]Catching String exceptions
I'm making a jTextField restrict integer input in netbeans and I don't know what to do. 我正在使jTextField限制netbeans中的整数输入,但我不知道该怎么办。 I'm doing it like this:
我正在这样做:
private void txtNameKeyReleased(java.awt.event.KeyEvent evt) {
try {
String j = (String) txtName.getText();
} catch ("Which Exception to Catch?") {
if (!txtAge.getText().isEmpty()) {
jOptionPane1.showMessageDialog(null,
"Please enter string values");
txtAge.setText(txtAge.getText().replaceAll("[^a-z]", ""));
}
}
}
What should I put on the catch? 我应该抓住什么?
You could just test the input against a regular expression using String.matches()
to make sure it's only digits (no need to catch an exception such as a NumberFormatException
- it can be considered bad practice to provoke exceptions to validate conditions). 您可以使用
String.matches()
针对正则表达式测试输入,以确保输入仅是数字(无需捕获诸如NumberFormatException
类的异常-引发异常以验证条件可被视为不良做法)。
String j = txtAge.getText();
if (!j.matches("\\d+")) {
// It is not a number
}
If you just want to try to convert to an Integer
directly and catch an exception you should use Integer.parseInt()
(it will throw a NumberFormatException
if the input can't be parsed as an Integer
): 如果您只想尝试直接转换为
Integer
并捕获异常,则应使用Integer.parseInt()
(如果无法将输入解析为Integer
,则会抛出NumberFormatException
):
String j = txtAge.getText();
try {
Integer i = Integer.parseInt(txtAge);
}
catch (NumberFormatException e) {
// j isn't a number...
}
EDIT : There seems to be a little confusion with the answer you provided. 编辑 :您提供的答案似乎有些混乱。 In your question the error message was Please enter integer values , as if valid input was only digits.
在您的问题中,错误消息是“ 请输入整数值” ,就像有效输入只是数字一样。 In the answer you posted the message was Please enter String values .
在您发布的答案中,消息为“ 请输入字符串值” 。
If you want to validate the input doesn't have any numbers, you'll have to use another regex, such as .*\\\\d.*"
. If it matches, it means it has a digit. Or you could also use \\\\D+
to ensure it has one or more non-digits . 如果要验证输入没有任何数字,则必须使用其他正则表达式,例如
.*\\\\d.*"
。如果匹配,则表示它有一个数字。或者您也可以使用\\\\D+
以确保它具有一个或多个非数字 。
I've solved my problem like this: 我已经解决了这样的问题:
private void txtNameKeyReleased(java.awt.event.KeyEvent evt) {
String j = (String)txtName.getText();
if ( j.matches("\\d+") && !txtName.getText().isEmpty()) {
jOptionPane1.showMessageDialog(null, "Please enter String values");
txtName.setText("");
} }
Thanks for the ones who tried to help me :) 感谢那些试图帮助我的人:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.