【问题标题】:prevent users for using certain characters in a calculator防止用户在计算器中使用某些字符
【发布时间】:2014-10-19 19:35:50
【问题描述】:

我正在制作一个计算器,我想抛出一个窗口,其中显示一条消息,说只接受数字,以防用户在 textField 中键入一个不是数字的字符,所以这就是我所做的并且根本没用。 感谢阅读。

private void txtPantallaActionPerformed(java.awt.event.ActionEvent evt) {                                            
    String invalids;
    invalids = "|@#¢∞¬÷“”≠´‚πø  ¥†®€æœå∫∂ƒ™¶§ ~–…„µ ß√©∑Ωqwertyuiopñlkjhgfdsazxcvbnm!$%&/=?¿*^QWERTYUIOPÑLKJHGFDSAZXCVBNM";
    for (int i = 0 ; i < invalids.length() ; i++)
    {
        if(txtPantalla.getText().equals (invalids.substring(i, i+1)))
        {
            JOptionPane.showMessageDialog(null,"Only works with numbers");
        }
    }


}

【问题讨论】:

  • 为什么不只吃按键,那应该可以很好地传递信息。

标签: java user-interface calculator


【解决方案1】:

您可以使用正则表达式来提高可读性并避免循环:

String value = txtPantalla.getText();
if(Pattern.matches(".*[^0-9].*", value)) {
  // there are some invalid characters!
  JOptionPane.showMessageDialog(null, "Only works with numbers");
}

任何需要硬编码的解决方案都可能是错误的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多