我试图从一个多项式字符串中提取系数和指数,然后将它们存储到一个数组中,这样我就可以使用这些数组来创建一个可以对其进行数学运算的新项(例如,加、减和乘)。
List<Term> poly = new ArrayList<>;
String poly = "26x^7+5x^6-8x^3-2";
int[] coeff = // Something like using split method here to get coeffs
int[] expo = // Same here but with exponents
for(int i = 0; i < coeffs.length; i++){
poly.add(new Term(coeff[i], expo[i]);
}问题是,我真的不知道该怎么做。我尝试了很多方法,但都导致了一个错误..
发布于 2019-05-08 21:28:54
我会尝试使用"+“或"-”字符拆分多维字符串。如果java中有正则表达式拆分方法,那将是合适的。
拆分得到的数组是应该在循环中迭代的数组,以便填充poly。
另一件要注意的事情是多项式中的"-2“项,从技术上讲,它是x^0,任何"ax”项,都是x^1。
发布于 2019-05-08 21:39:11
这里有一个解决方案,它忽略了x^1、x^0和coefficient=1带来的额外复杂性。
它在正则表达式中使用Lookahead,如here所述
import java.util.ArrayList;
import java.util.List;
public class MyClass {
public static void main(String[] args) {
// expect format ax^n for each term. in particular in the cases a=1, x=1 and x=0.
String poly = "26x^7+5x^6-8x^3+1x^1-2x^0";
// remove ^ and then split by x and by + and - keeping the sign
String[] numbers = poly.replace("^", "").split("((?=\\+)|(?=\\-)|x)");
List<Integer> coeff = new ArrayList<>();
List<Integer> expo = new ArrayList<>();
// we can now assume that for every coefficient there is an exponent
for (int i = 0; i < numbers.length; i += 2) {
coeff.add(Integer.parseInt(numbers[i]));
expo.add(Integer.parseInt(numbers[i + 1]));
}
System.out.println(coeff);
System.out.println(expo);
}
}输出:
[26, 5, -8, 1, -2]
[7, 6, 3, 1, 0]https://stackoverflow.com/questions/56041285
复制相似问题