java - 如何验证输入的文本是否为数字?

标签 java swing programming-languages validation joptionpane

我有一个计算应用程序,我需要验证字段以检查输入的值是否是数字而不是字母数字。我对代码有一些想法。
如果我做错了什么或者看起来很菜鸟,请指导我,因为这是我第一次尝试 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”命令?

最佳答案

如果 String 不是数字且无法解析为 Float,

Float.parseFloat() 将抛出 NumberFormatException 。您可以添加 try-catch block 来检查此条件:

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

关于java - 如何验证输入的文本是否为数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3412135/

相关文章:

java - Selenium - 创建 UI 驱动的自动化框架

java - 如何使用 webdriver 在鼠标悬停时保持下拉菜单打开

java - 泛型返回类型有什么用

java - 如何在 JFrame 和 JPanel 中设置玻璃 Pane 的位置

oop - 是否有任何 OO 语言允许从类中减去特征?

java - Selenium Webdriver - 验证文本框写保护?

java - 没有在 Java 中调用 paintComponents 方法

Java 身份验证程序问题

programming-languages - 区分大小写的语言比不区分大小写的语言有什么优势?

ruby - 为什么 Ruby 的项目似乎比其他编程语言少?