Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 不使用正则表达式和API计算多项式字符串_Java_Polynomial Math - Fatal编程技术网

Java 不使用正则表达式和API计算多项式字符串

Java 不使用正则表达式和API计算多项式字符串,java,polynomial-math,Java,Polynomial Math,给定一个单变量x的多项式,以x的值作为输入,计算其值。示例: 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 {

给定一个单变量x的多项式,以x的值作为输入,计算其值。示例:

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;
    }
}
公共类EvalPolyX2{
静态字符串testcase1=“-2x^3+10x-4x^2”;
静态字符串testcase2=“3”;
公共静态void main(字符串参数[]){
EvalPolyX2 testInstance=新的EvalPolyX2();
int result=testInstance.eval(testcase1、testcase2);
System.out.println(“结果:+Result”);
}
公共整数评估(字符串str,字符串valx){
整数和=0;
字符串subStr=“”;
如果(str.charAt(0)='-')
{
int len=str.length();
对于(int i=0;i
简单的答案是,当您这样做时:

           if(str.charAt(i) == '-' || str.charAt(i) == '+')
            {
                subStr = str.substring(0, i);
其效果是将subStr设置为-或+之前的文本,并对其进行计算。但是,由于字符串末尾没有-或+,因此该逻辑无法计算多项式的最后一项,因为它只计算-或+前面的子字符串


另外,这只是我注意到的一个问题。我不知道其余的逻辑是否正确。

解析字符串时,查找+/-,只有找到了才停止。这适用于前两个术语,但当您使用“-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);
    }
if(str.charAt(0)='-')
{
int len=str.length();
对于(int i=0;i
我还将抛出免责声明,可能会有更多的错误,但这是导致您的问题的主要原因


编辑:将更改添加到
else if
语句中,并添加了我在上面的评论中提到的更改

此代码替换应该会有所帮助

  if(str.charAt(i) == '-' || str.charAt(i) == '+' || i == (len - 1))
  {   
    if(i == len - 1)
    {
     i++;
    }
    ...
虽然还有更好的方法,但我只想在这里展示一条出路。 原因是您正在寻找+或-作为分隔符。 但表达式的最后一部分不会以这两个结尾,而可能是EOL

  • 您需要考虑最后一个术语(if语句仅在找到
    -
    +
    时才会触发,但末尾没有)

    一种简单的方法是更换:

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

  • 处理
    +
    时也有一个bug。我得到了一个
    NumberFormatException
    。处理它的一种方法是忽略术语之间的
    +
    (而不是在开头添加
    +
    ):

  • <
    //                 v one more iteration
    for (int i = 0; i <= len; i++)
    {
        if (i == len || str.charAt(i) == '-' || str.charAt(i) == '+')
    //      \------/
    //   extra condition
    
    if (str.charAt(0) == '-')
    {
      // common code
    }
    else if (str.charAt(0) != '-')
    {
      str = '+' + str;
      // common code
    }
    
    if (str.charAt(0) != '-')
    {
      str = '+' + str;
    }
    // common code
    
    if (i != len && str.charAt(i) == '+')
      str = str.substring(i+1);
    else
      str = str.substring(i);
    
    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
    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;
        }
    }