62,614
社区成员
发帖
与我相关
我的任务
分享
try {
String sourceString = "2x^3 - 1.1x^2+ 0.9x-1.4=0";
System.out.println(sourceString);
sourceString = sourceString.replaceAll("\\s", "");//先将式子中的空白符消除
System.out.println(sourceString);
//然后扫描它,如果缺少x3 就补 +0x^3,
//如果缺少x2 就补 +0x^2,
//如果缺少x 就补 +0^x,
//如果缺少常数 就补+0,
//同时维持顺序,总之要保证“标准的”,下面的步骤才能顺利执行
if(sourceString.indexOf("x^3") == -1){
sourceString = "+0x^3" + sourceString;
}
if(sourceString.indexOf("x^2") == -1){
int pos = sourceString.indexOf("x^3") ;
sourceString = sourceString.substring(0,pos+3)+"+0x^2" + sourceString.substring(pos+3);
}
if(sourceString.lastIndexOf("x") == sourceString.indexOf("x^2")){
int pos = sourceString.indexOf("x^2") ;
sourceString = sourceString.substring(0,pos+3)+"+0x" + sourceString.substring(pos+3);
}
if(sourceString.lastIndexOf("x") +1 == sourceString.indexOf("=")){
int pos = sourceString.lastIndexOf("x") ;
sourceString = sourceString.substring(0,pos+1)+"+0" + sourceString.substring(pos+1);
}
String regex = "^(.+)x\\^3(.+)x\\^2(.+)x(.+)=0$";//这里只有提取功能,还无法进行验证
Matcher matcher = Pattern.compile(regex).matcher(sourceString);//
if(matcher.matches()){ ;
double a = Double.parseDouble(matcher.group(1));//如果系数>0 自动会将+去除
double b = Double.parseDouble(matcher.group(2));//如果系数不是常数,她是一个表达式
double c = Double.parseDouble(matcher.group(3));//比如系数是(3y + 4z) 此时应该进行更复杂的处理
double d = Double.parseDouble(matcher.group(4));
System.out.println(a + " " + b + " " + c + " " + d); }
}catch (Exception e) {
throw new Exception("输入错误");
}
try {
String regex = "(.+)x\\^3[\\s]*[+\\-][\\s]*(.+)x\\^2[\\s]*[+\\-][\\s]*(.+)x[\\s]*[+\\-][\\s]*(.+)[\\s]*=.*";
String sourceString = "2x^3+1.1x^2+0.9x-1.4=0";
Matcher matcher = Pattern.compile(regex).matcher(sourceString);//
if(matcher.matches()){ ;
double a = Double.parseDouble(matcher.group(1));
double b = Double.parseDouble(matcher.group(2));
double c = Double.parseDouble(matcher.group(3));
double d = Double.parseDouble(matcher.group(4));
System.out.println(a + " " + b + " " + c + " " + d);
}
}catch (Exception e) {
throw new Exception("输入错误");
}