-1

这是我试图将任何数学方程变量的系数固定为相同变量的总和系数,如“x^2+x^2+2x-x-25”为“+1x^2+1x^2+2x- 1x-25”,然后求和为“2x^2+x-25”,注意我已经用另一种方法完成了求和过程。

private static String fixCoeff(String equ)
{
    equ=equ.toLowerCase();//change equation variables to lower case
    equ=equ.trim();//remove white spaces
    String []characters={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
    int index=-1;
    String fixedCoeff="";
    for (int i = 0; i < characters.length; i++)
    {
        if(!equ.contains(characters[i]))
        {
            continue;
        }
        //if a not found in equ i++ 
        //if true execute this
        while(equ.indexOf(characters[i],++index)!=-1)
        {


            index=equ.indexOf(characters[i]);
            if(index==0)
            {
                fixedCoeff+="+1"+equ;
                equ=fixedCoeff;
                index=2;
                break;

            }
            else
            {

                if (equ.charAt(index-1)=='+'||equ.charAt(index-1)=='-')
                {
                    fixedCoeff=equ.substring(-1,index-1);
                    fixedCoeff+="1"+equ.substring(index-1,equ.length()-1);
                    equ=fixedCoeff;
                    index++;
                    break;
                }

            }

        //  if (index==equ.length()-1) {//if we found last element in equ is a variable
                //break;
            //}
        }//end while

    }//end for loop 


    return equ;

}//end fixCoeff

输入案例:

  1. 一个
  2. X
  3. x^2
  4. x^2+x^2

输出案例:

  1. +1a
  2. +1x
  3. +1x^2
  4. +1x^2+1x^2
4

2 回答 2

2

只是为了加起来@brso05的答案,

这是另一种方法:

    String s ="x^2+x^2+2x-x-25";
    s=s.replaceAll("(?<!\\d)([a-z])", "1$1");    // <-- replaces any lower letters with 1 concatanted with the same letter
    if(!s.startsWith("-")){
        s="+"+s;  //<-- if the first character is not negative add a + to it.
    }
    System.out.println(s);

输出:

+1x^2+1x^2+2x-1x-25
于 2015-05-22T15:19:00.330 回答
1

您可以使用以下方法更轻松地完成String.replaceAll()此操作:

for (int i = 0; i < characters.length; i++)
{
    if(!equ.contains(characters[i]))
    {
        continue;
    }
    equ = equ.replaceAll(("(?<!\\d)" + characters[i]), ("1" + characters[i]));
}
if(!equ.startsWith("-") && !equ.startsWith("+"))
{
    equ = "+" + equ;
}

这会将前面没有数字的字符替换为 1x(或任何当前字符)。这使用正则表达式和负向后看,以确保字符前面没有数字,然后它将替换为 1(字符)。

这是一个独立的示例:

String line = "x-x^2+3x^3";
line = line.replaceAll("(?<!\\d)x", "1x");
System.out.println("" + line);

这将输出1x-1x^2+3x^3.

于 2015-05-22T15:12:23.580 回答