2013-08-22 30 views
5

给定一个具有单个变量x的多项式,并将x的值作为输入,计算其值。实例:不使用正则表达式和API评估多项式字符串

eval("-2x^3+10x-4x^2","3")=-60 

eval("x^3+x^2+x","6")=258 

问题的描述:在此代码我打破串入一个子每当+/-遇到和子串传递给其评估像“-2x^3”单项的函数。所以我的输入代码=“-2x^3 + 10x-4x^2”只计算到“-2x^3 + 10x”,并跳过“-4x^2”部分。

任何人都可以告诉我什么是错的吗?

public class EvalPolyX2 { 

    static String testcase1 = "-2x^3+10x-4x^2"; 
    static String testcase2 = "3"; 

    public static void main(String args[]){ 
     EvalPolyX2 testInstance = new EvalPolyX2(); 
     int result = testInstance.eval(testcase1,testcase2); 
     System.out.println("Result : "+result); 
    } 

    public int eval(String str,String valx){ 

     int sum = 0;   
     String subStr = ""; 
     if(str.charAt(0) == '-') 
     { 
      int len = str.length(); 
      for (int i = 0; i < len; i++) 
      { 
       if(str.charAt(i) == '-' || str.charAt(i) == '+') 
       {     
        subStr = str.substring(0, i); 
        System.out.println("subStr="+subStr); 
        sum += evalSubPoly(subStr, valx); 
        str = str.substring(i); 
        len = str.length(); 
        i = 0; 
       }    
      } 
     } 
     else if(str.charAt(0) != '-') 
     { 
      str = '+' + str; 
      int len = str.length(); 
      for (int i = 0; i < len; i++) 
      { 
       if(str.charAt(i) == '-' || str.charAt(i) == '+') 
       { 
        subStr = str.substring(0, i); 
        System.out.println("subStr="+subStr); 
        sum += evalSubPoly(subStr, valx); 
        str = str.substring(i); 
        len = str.length(); 
        i=0; 
       } 
      } 
     } 
     return sum; 
    } 

    public int evalSubPoly(String poly,String valx){ 
     int len = poly.length(); 
     String num = ""; 
     String power = ""; 
     int exp = 0, coeff = 0; 

     for(int i = 0; i < len; i++) 
     { 
      if(poly.charAt(i) == 'x') 
      { 
       num = poly.substring(0, i); 
       coeff = Integer.parseInt(num);        
      } 
      if(poly.charAt(i) == '^') 
      { 
       power = poly.substring(i+1, len); 
       exp = Integer.parseInt(power); 
      }      
     } 

     if(power.equals("")) 
      exp = 1; 
     System.out.println("coeff="+coeff); 

     int sum = 1; 
     int x = Integer.parseInt(valx); 

     for (int i = 0; i < exp; i++) 
     { 
      sum = sum*x; 
     } 
     System.out.println("sum="+sum); 
     sum = sum*coeff; 

     return sum; 
    } 
} 
+0

让我改一下 - 当试图运行的代码示例为是,我得到'线程“main” java.lang.NumberFormatException例外:对于输入字符串:“+10”'。这意味着您的代码示例不会重现问题,这会让我们的生活更加困难。 – Dukeling

+0

Dukeling是对的,因为你在找到它之后在字符串中包含+/-符号。为了避免这种情况,你需要将'str = str.substring(i);'改为'str = str.substring(i + 1);'这样,字符串的其余部分在+/-之后开始,而不是包括它。 –

+0

但是,如果它是' - ',他不需要包含它吗?否则,它的' - '而不是'+'会完全丢失。 – ajb

回答

1

提到增加变化该代码替换应有助于

if(str.charAt(i) == '-' || str.charAt(i) == '+' || i == (len - 1)) 
    { 
    if(i == len - 1) 
    { 
    i++; 
    } 
    ... 

虽然有可能是更好的方式,但我只是想表明一种方式在这里。 原因是你正在寻找+或 - 作为分隔符。 但表达的最后部分不会与这些,但最终只可能EOL

+0

你和@ Dukeling的建议结合起来了!谢谢。 – abhishek14d

0

简单的答案是,当你这样做:

  if(str.charAt(i) == '-' || str.charAt(i) == '+') 
      { 
       subStr = str.substring(0, i); 

的效果是你设置SUBSTR文本只是之前 - 或+,并评估它。但是由于在字符串末尾没有 - 或+,因此该逻辑将无法评估多项式的​​最后一项,因为它只评估正好在 - 或+之前的子字符串。

P.S.这只是我注意到的一个问题。我不知道其余的逻辑是否正确。

0

当您解析字符串时,您会查找+/-,并且只有在找到它们时才会停止。这适用于前两项,但是当你下降到“-4x^2”时,循环不会停止,因为没有+/-。因此,除了您拥有的条件之外,您还需要添加代码,以便在到达字符串末尾时,剩下的就是最后一个词。所以,你想拥有这是什么

if(str.charAt(0) == '-') 
    { 
     int len = str.length(); 
     for (int i = 0; i < len; i++) 
     { 
      if(str.charAt(i) == '-' || str.charAt(i) == '+') 
      {     
       subStr = str.substring(0, i); 
       System.out.println("subStr="+subStr); 
       sum += evalSubPoly(subStr, valx); 
       str = str.substring(i+1); 
       len = str.length(); 
       i = 0; 
      }    
     } 
     System.out.println("subStr="+str); 
     sum += evalSubPoly(str, valx); 
    } 


    else if(str.charAt(0) != '-') 
    { 
     str = '+' + str; 
     int len = str.length(); 
     for (int i = 0; i < len; i++) 
     { 
      if(str.charAt(i) == '-' || str.charAt(i) == '+') 
      { 
       subStr = str.substring(0, i); 
       System.out.println("subStr="+subStr); 
       sum += evalSubPoly(subStr, valx); 
       str = str.substring(i+1); 
       len = str.length(); 
       i=0; 
      } 
     } 
     System.out.println("subStr="+str); 
     sum += evalSubPoly(str, valx); 
    } 

我也会抛出免责声明可能会有更多的错误,但是这是一个主要的造成您的问题。

编辑:添加更改else if说法,在我的评论上述

1
  1. 你需要考虑的最后一项(当-+发现if语句才会触发,这在最后没有)。

    一个简单的方法做,这是替换:

    for (int i = 0; i < len; i++) 
    { 
        if (str.charAt(i) == '-' || str.charAt(i) == '+') 
    

    有:

    //     v one more iteration 
    for (int i = 0; i <= len; i++) 
    { 
        if (i == len || str.charAt(i) == '-' || str.charAt(i) == '+') 
    //  \------/ 
    // extra condition 
    

    以上只是去上多了一个迭代,在该迭代,总是进入,如果 - 陈述,导致最后一个词被处理。

  2. 您还可以简化

    if (str.charAt(0) == '-') 
    { 
        // common code 
    } 
    else if (str.charAt(0) != '-') 
    { 
        str = '+' + str; 
        // common code 
    } 
    

    要:

    if (str.charAt(0) != '-') 
    { 
        str = '+' + str; 
    } 
    // common code 
    
  3. 还有与处理+的错误。我为此得到了一个NumberFormatException。来处理它的方法之一是忽略的条款之间的+(而不是增加一个+到开始):

    if (i != len && str.charAt(i) == '+') 
        str = str.substring(i+1); 
    else 
        str = str.substring(i); 
    
  4. 而且你还不如让你的函数static,并呼吁他们,而不是直接宣布新你的班级的实例。

Test

+1

其实它应该是(i == len-1)里面的if。有效。谢谢! – abhishek14d

+1

@ abhishek14d ['i == len'似乎正常工作。](https://ideone.com/ikOFlX)对我的答案做了一些补充。 – Dukeling

2

使用正则表达式有什么问题?您可以将多项式分解为单项式,对每个项进行评估,并添加所有结果。

private static final Pattern monomial = Pattern 
     .compile("([+-])?(\\d+)?x(?:\\^(\\d+))?"); 

public static int eval(String str, String valx) { 
    Matcher m = monomial.matcher(str); 
    int x = Integer.parseInt(valx); 

    int total = 0; 
    while (m.find()) { 
     String mul = m.group(2); 
     int value = (mul == null) ? 1 : Integer.parseInt(m.group(2)); 

     String pow = m.group(3); 
     value *= (pow == null) ? x : (int) Math.pow(x, 
       Integer.parseInt(pow)); 

     if ("-".equals(m.group(1))) 
      value = -value; 

     total += value; 
    } 

    return total; 
} 

System.out.println(eval("-2x^3+10x-4x^2", "3")); 
System.out.println(eval("x^3+x^2+x", "6")); 
 
-60 
258 
+0

绝对是最清晰的(这与我将使用的完全相同的正则表达式),但标题使我认为这是一个类的任务和正则表达式被禁止。 – ajb

0

使用正则表达式,你可以得到一个更简单的解决方案。而且,你想要支持简单的常量吗?尝试下:

public class EvalPolyX2 { 
    public static void main(String args[]) { 
     System.out.println("Result: " + eval("x^3+x^2+x", 6)); 
    } 
    public static int eval(String eq, int val) { 
     int result = 0; 
     String mons[] = eq.split("(?=[+-])(?!\\B)"); 
     for (String str : mons) { 
      str = str.replace("+", ""); 
      if (str.contains("x")) { 
       double a = 1, b = 1; 
       String[] comps = str.split("x\\^?"); 
       if (comps.length > 0) { 
        a = comps[0].isEmpty() ? 1 : Integer.parseInt(comps[0]); 
       } 
       if (comps.length > 1) { 
        b = Integer.parseInt(comps[1]); 
       } 
       result += a * Math.pow(val, b); 
      } else { 
       result += Integer.parseInt(str); 
      } 
     } 
     return result; 
    } 
} 
相关问题