【问题标题】:Number Format Exception and Regex Inquiry数字格式异常和正则表达式查询
【发布时间】:2015-05-04 13:12:52
【问题描述】:

我正在尝试从用户那里获取一个数学表达式,但在这里我不断收到数字格式异常:

Exception in thread "JavaFX Application Thread" java.lang.NumberFormatException: For input string: "(13-1)*(12-10)"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:569)
    at java.lang.Integer.valueOf(Integer.java:766)
    at Main.lambda$start$2(Main.java:134)
    at Main$$Lambda$73/16094097.handle(Unknown Source)

这是我用来评估输入表达式的事件处理程序。文本字段应该接受 4 个数字 (1-13) 的表达式并评估它是否等于 24。我正在使用正则表达式,但它似乎不起作用。另外,我有一个字符数组,我最初只用于标志,但这似乎没有必要。我对正则表达式非常陌生,并且已经尝试了多种组合。

btVerify.setOnAction(
            (ActionEvent e) -> 
            {
               LinkedList<Character> expInput = new LinkedList<Character>();
            for(char c: tfExpress.getText().toCharArray()){
                expInput.add(c);
                }
            String[] inputIntegers = tfExpress.getText().split("[^0-9]+-/*()");

               expInput.removeIf(p-> p.equals(signs));

            ArrayList<Integer> temp = new ArrayList<>();
            for(String s:inputIntegers)
            {
               temp.add(new Integer(Integer.valueOf(s)));
            } 
            temp.remove(new Integer(card1.CardValue()));
            temp.remove(new Integer(card2.CardValue()));                    
            temp.remove(new Integer(card3.CardValue()));          
            temp.remove(new Integer(card4.CardValue()));          


               if(temp.isEmpty()&& expInput.isEmpty())
               {
                  if(express == 24){
                     display.setText("Correct");
                  }
                  else
                     display.setText("Incorrect");

               }
               else
                  display.setText("The numbers in the expression don't "
                     + "match the numbers in the set.");
            });

【问题讨论】:

  • 除了你的正则表达式之外,signs 是什么?
  • 符号是我之前尝试创建的字符数组列表。我把它留在了代码中,但它目前不起作用。我还在 if 语句中尝试了 (temp.isEmpty()) ,但这也不起作用。

标签: java regex arraylist javafx linked-list


【解决方案1】:

NumberFormat Exception 是因为您的正则表达式没有将数字与符号/文字分开。

tfExpress.getText().split("[^0-9]+-/*()"); 

返回整个文本,即(13-1)*(12-10)

您需要一个更复杂的正则表达式,它将符号与数字分开。感谢@unihedron 提供正则表达式。

\b|(?<=[()])(?=[^\d()])|(?<=[^\d()])(?=[()])

现在你可以使用了

...
String regex = "\b|(?<=[()])(?=[^\d()])|(?<=[^\d()])(?=[()])";
tfExpress.getText().split(regex);
... 

一个非常简单的工作示例可以是found here

【讨论】:

  • 非常感谢您!有什么理由告诉我“d”是非法转义字符?
【解决方案2】:

我希望您不要期望使用正则表达式来评估该公式。那是行不通的。

对于拆分,如果您不知道正则表达式,请使用 StringTokenizer 之类的其他东西。

StringTokenizer t = new StringTokenizer( "(13-1)*(12-10)", "+-/*()", true);
while( t.hasMoreTokens()) {
  System.out.println(t.nextToken());
}

结果

(
13
-
1
)
*
(
12
-
10
)

【讨论】:

  • 好的,谢谢。如何将它用于我不知道值的表达式?每次都会有所不同。
猜你喜欢
  • 1970-01-01
  • 2014-10-08
  • 2010-11-18
  • 1970-01-01
  • 1970-01-01
  • 2011-08-05
  • 1970-01-01
相关资源
最近更新 更多