Java程序从二次方程中提取系数
问题:Java程序将系数从二次方程中拆分,例如,如果输入字符串是:
String str1;
str1 = "4x2-4x-42=0"
所以我需要分割给定输入字符串的系数并得到输出
a = 4 b = -4 c = -42
我试过这个:
String equation = "ax2+bx-c=0";
String[] parts = equation.split("+|-|=");
for (int i = 0; i < parts.length - 2; i++) {
String part = parts[i].toLowerCase();
System.out.println(part.substring(0, part.indexOf("x")));
}
System.out.println(parts[2]);
但是我得到了23x2和4x和4的输出。实际输出需要是23 ,- 4 , 4
。
使用正则表达式,以下模式将起作用:
([+-]?d+)[Xx]2s*([+-]?d+)[Xx]s*([+-]?d+)s*=s*0
这将匹配二次方程并提取参数,让我们弄清楚它的工作原理:
(...)
这是捕获组 [+-]?d+
匹配多个数字,前面可以加上+
或-
[Xx]
匹配“X”或“x” s*
这个匹配零个或多个空格 所以
([+-]?d+)
与“a”参数匹配 [Xx]2
匹配“X2”或“x2” s*
匹配可选的空格 ([+-]?d+)
与“b”参数匹配 [Xx]
匹配“X”或“x” s*
匹配可选的空格 ([+-]?d+)
与“c”参数匹配 s*=s*0
与某些可选空格匹配“= 0” 让我们把它包装在一个class
:
private static final class QuadraticEq {
private static final Pattern EQN = Pattern.compile("([+-]?d+)[Xx]2s*([+-]?d+)[Xx]s*([+-]?d+)s*=s*0");
private final int a;
private final int b;
private final int c;
private QuadraticEq(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
public static QuadraticEq parseString(final String eq) {
final Matcher matcher = EQN.matcher(eq);
if (!matcher.matches()) {
throw new IllegalArgumentException("Not a valid pattern " + eq);
}
final int a = Integer.parseInt(matcher.group(1));
final int b = Integer.parseInt(matcher.group(2));
final int c = Integer.parseInt(matcher.group(3));
return new QuadraticEq(a, b, c);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("QuadraticEq{");
sb.append("a=").append(a);
sb.append(", b=").append(b);
sb.append(", c=").append(c);
sb.append('}');
return sb.toString();
}
}
注意 ,这是Java所要求的。
快速测试:
System.out.println(QuadraticEq.parseString("4x2-4x-42=0"));
输出:
QuadraticEq{a=4, b=-4, c=-42}
你可以使用一个正则表达式,如下所示:
final String regex = "([+-]?d+)x2([+-]d+)x([+-]d+)=0";
Pattern pattern = Pattern.compile(regex);
final String equation = "4x2-4x-42=0";
Matcher matcher = pattern.matcher(equation);
if (matcher.matches()) {
int a = Integer.parseInt(matcher.group(1));
int b = Integer.parseInt(matcher.group(2));
int c = Integer.parseInt(matcher.group(3));
System.out.println("a=" + a + " b=" + b + " c=" + c);
}
输出:
a=4 b=-4 c=-42
如果你只使用quadratics:
int xsqrd = equation.indexOf("x2");
int x = equation.indexOf("x", xsqrd);
int equ = equation.indexOf("=");
String a = equation.subString(0,xsqrd);
String b = equation.subString(xsqrd+1,x);
String c = equation.subString(x,equ);
我可能搞乱了子串,但你得到了一般想法。
链接地址: http://www.djcxy.com/p/84529.html上一篇: Java program to extract coefficents from quadratic equation