【问题标题】:How can I make users ONLY input decimal?如何让用户只输入十进制?
【发布时间】:2013-11-26 17:08:26
【问题描述】:

所以我对 java 很陌生,并且在课堂上苦苦挣扎......这就是我认为可行的方法:

double costPerKiloHr = 0; //sets value to 0

    //tests to make sure a number was inputted

        try {
            costPerKiloHr = Double.parseDouble(
                this.costPerKiloHrText.getText());
        }   
        catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Please input a dollar amount including cents",
                    "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

【问题讨论】:

  • 这不行吗?您收到什么错误消息?
  • 您的解决方案有什么问题?
  • 它允许数字,小数或不。对不起,我应该这么说的。
  • 您可以在尝试解析文本之前使用正则表达式来验证文本是否为有效数字 - 如果您希望即使用户也能够获取数字,也可以提供 NumberFormat输入美元符号或任何类似的东西。
  • 那它怎么不工作呢?我假设您的意思是您唯一不想要的是字母文本,但所有其他数值都有效吗?例如,所有整数都是有效的(计数,自然和负数)以及小数?使用正则表达式可能会更好。

标签: java input decimal


【解决方案1】:

您可以使用正则表达式检查小数点后至少 1 个数值是否匹配。

    String input = scanner.next();
    Pattern pattern = Pattern.compile("[0-9]*\\.[0-9]+");
    Matcher matcher = pattern.matcher(input);
    if(matcher.matches()){
        System.out.println("True");
    }else{
        System.out.println("False");
    }

输出

1.0   True
ASB   False
0.25  True
1     False

【讨论】:

    【解决方案2】:

    你不能让用户输入你想要的,如果你不是一个法师或smth。但是您可以编辑接受用户输入的代码。可能会有很大的不同:我不知道您使用什么作为输入。我注意到您使用的是JOptionPane,所以我猜您使用的是 swing。

    在swing中有JTextField,你可以像这样控制它的内容:

        final JTextField field = new JTextField();
        field.addKeyListener(new KeyListener() {
    
            StringBuilder buffer = new StringBuilder();
    
            @Override
            public void keyTyped(KeyEvent e) {
                char c = e.getKeyChar();
                if (Character.isDigit(c)) {
                    buffer.append(c);
                }
            }
    
            @Override
            public void keyPressed(KeyEvent e) {
            }
    
            @Override
            public void keyReleased(KeyEvent e) {
                field.setText(buffer.toString());
            }
        });
    

    如果您使用InputStream,则应将byte 对解释为chars,然后过滤掉非数字值。这种方式需要声明分隔符。

    【讨论】:

      【解决方案3】:

      假设您使用的是 Swing(使用 JOptionPane 是一个安全的选择),您可以让用户键入 javax.swing.JFormattedTextField... 这是 JTextField 小部件的扩展,它采用 Formatter 对象它定义了什么是可接受的,什么是不可接受的。它可以配置(通过Formatter.setAllowsInvalid(false))永远不允许用户输入无效的字符串。

      因此,任意正则表达式的格式化程序可能如下所示:

      public class RegExFormatter extends DefaultFormatter {
              protected Matcher matcher;
              public RegExFormatter(String regex) {
              setOverwriteMode(false);
              Pattern p = Pattern.compile(regex);
              matcher = p.matcher(""); // initial field contents
          }
      
          @Override
          public Object stringToValue(String string) throws ParseException {
              if (string == null || string.trim().equals(""))
                  return null;
              matcher.reset(string);
      
              if (!matcher.matches()) {
                  throw new ParseException("Input did not match regex", 0);
              }
      
              return super.stringToValue(string);  // default returns this string; see docs!
          }
      
      }
      

      然后你在你的代码中这样使用它:

          String regex = "^[1-9]*[0-9](\\.\\d*)?$";  // change this to taste!
          RegExFormatter ref = new RegExFormatter(regex);
          ref.setAllowsInvalid(false);
          JFormattedTextField field1 = new JFormattedTextField(ref);
      

      【讨论】:

        猜你喜欢
        • 2021-12-30
        • 2019-07-24
        • 2017-09-25
        • 1970-01-01
        • 2019-09-02
        • 1970-01-01
        • 1970-01-01
        • 2020-11-10
        • 1970-01-01
        相关资源
        最近更新 更多