有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

有问题的十进制格式。Java中的parse()

有一个要求,如果用户输入一个数字,解析它并doSomething()。 如果用户同时输入数字和字符串,则doSomethingElse()

因此,我编写了如下代码:

String userInput = getWhatUserEntered();
try {
   DecimalFormat decimalFormat = (DecimalFormat)     
   NumberFormat.getNumberInstance(<LocaleHere>);
   Number number = decimalFormat.parse(userInput);
   doSomething(number);    // If I reach here, I will doSomething

   return;
}
catch(Exception e)  {
  // Oh.. user has entered mixture of alpha and number
}

doSomethingElse(userInput);  // If I reach here, I will doSomethingElse
return;

函数getWhatUserEntered()如下所示

String getWhatUserEntered()
{
  return "1923";
  //return "Oh God 1923";
  //return "1923 Oh God";
}

但是,有一个问题

  • 当用户输入1923时doSomething()被击中
  • 当用户进入哦,上帝1923-->doSomethingElse()被击中
  • 当用户进入1923年时,哦,上帝doSomething()被击中。这是错误的 这里我需要doSomethingElse()应该被点击

我想实现的东西有没有内在的(更好的)功能? 我的代码可以根据需要修改吗


共 (3) 个答案

  1. # 1 楼答案

    您最好使用一些正则表达式,例如userInput.matches("[0-9]+")只用于匹配数字

  2. # 2 楼答案

    由于具体的DecimalFormat实现,一切正常。JavaDoc说:

    Parses text from the beginning of the given string to produce a number. The method may not use the entire text of the given string.

    因此,您必须将代码修改为以下内容:

      String userInput = getWhatUserEntered();
        try {
            NumberFormat formatter = NumberFormat.getInstance();
            ParsePosition position = new ParsePosition(0);
            Number number = formatter.parse(userInput, position);
            if (position.getIndex() != userInput.length())
                throw new ParseException("failed to parse entire string: " + userInput, position.getIndex());
            doSomething(number);    // If I reach here, I will doSomething
    
            return;
        }
        catch(Exception e)  {
            // Oh.. user has entered mixture of alpha and number
        }
    
        doSomethingElse(userInput);  // If I reach here, I will doSomethingElse
        return;
    
  3. # 3 楼答案

    DecimalFormat接受任何以数字开头的字符串

    您可以做的是执行额外的检查

    try {
      DecimalFormat decimalFormat = (DecimalFormat)     
      NumberFormat.getNumberInstance(<LocaleHere>);
      Number number = decimalFormat.parse(userInput);
      if (number.toString().equals(userInput)) {
        doSomething(number);    // If I reach here, I will doSomething   
        return;
      }
    }