如果文本字段不是数值,如何创建错误消息?
How to create error message if text field isn't a numeric value?
我正在尝试为 class 作业创建一个音乐会门票订购表,如果他们不在“数量”字段中键入数字,它就会将标签设置为 "Na"如果它是一个数值,则将该标签设置为该数值。我在 Java 还是新手,不知道该怎么做。
如果文本字段不是数值,如何创建错误消息?
评论区讨论后解决...
为了检查写在 jlabel 中的字符串 (test
) 是否是一个数字,我使用了 Integer.parseInt()
函数,如果这个字符串是数字,它会抛出“NumberFormatException
”不可转换为数值,尤其是整数。
解决方案
JLabel jLabel1 = new JLabel();
String test = jLabel2.getText();
try {
// Converts the string into a number
int value = Integer.parseInt(test);
// Set this number into the jlabel
jlabel1.setText(""+value);
} catch (NumberFormatException e) {
jLabel1.setText("Na");
}
如果您不知道如何使用 try-catch
,请看一下:The try block.
我正在尝试为 class 作业创建一个音乐会门票订购表,如果他们不在“数量”字段中键入数字,它就会将标签设置为 "Na"如果它是一个数值,则将该标签设置为该数值。我在 Java 还是新手,不知道该怎么做。
如果文本字段不是数值,如何创建错误消息?
评论区讨论后解决...
为了检查写在 jlabel 中的字符串 (test
) 是否是一个数字,我使用了 Integer.parseInt()
函数,如果这个字符串是数字,它会抛出“NumberFormatException
”不可转换为数值,尤其是整数。
解决方案
JLabel jLabel1 = new JLabel();
String test = jLabel2.getText();
try {
// Converts the string into a number
int value = Integer.parseInt(test);
// Set this number into the jlabel
jlabel1.setText(""+value);
} catch (NumberFormatException e) {
jLabel1.setText("Na");
}
如果您不知道如何使用 try-catch
,请看一下:The try block.