【问题标题】:Java program to extract coefficents from quadratic equationJava程序从二次方程中提取系数
【发布时间】:2015-04-18 16:51:57
【问题描述】:

问题: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

【问题讨论】:

  • 所以输入的格式总是+/-aX2+/-bX+/-c?听起来像是……正则表达式的工作。
  • 是的。始终采用这种格式
  • 你只需要系数吗?如果您以后也打算获得指数,我建议为您的表达式构建一个小型解析器。
  • 我只需要系数。如果输入字符串是“4x2-4x-42=0”和“a=4 b=-4 c = -42”,这应该是输出

标签: java regex string math


【解决方案1】:

使用正则表达式,以下模式将起作用:

([+-]?\d+)[Xx]2\s*([+-]?\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]2\\s*([+-]?\\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}

【讨论】:

  • 错误:类型Matcher中的方法组(int)不适用于参数(String)
  • final int a = Integer.parseInt(matcher.group("a")); final int b = Integer.parseInt(matcher.group("b")); final int c = Integer.parseInt(matcher.group("c"));
  • @JoeMathew 你是在告诉我你正在使用 Java 6 吗?它已有十多年的历史,两年前达到 EOL。为什么??
  • 先生,我在我的新安卓应用中使用它,有什么办法可以修改它
  • @JoeMathew 您的问题未标记为android。为什么?不要使用命名组,按索引获取组。
【解决方案2】:

如果你只使用二次方程:

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);

我可能弄乱了子字符串,但你明白了。

【讨论】:

  • 如果输入字符串是“4x2-4x-42=0”和“a=4 b=-4 c = -42”,这段代码会得到这个输出吗
【解决方案3】:

第一个注意事项:如果你在正则表达式中使用符号作为分隔符,你会在 slpitted 元素中丢失它。我建议您使用以下正则表达式:

"x2|x|="

那么,你只能得到数字。 完整的代码片段是:

public class Main {
    private static final char[] varNames = {'a', 'b', 'c'};

    public static void main(String[] args) {
        String equation = "4x2-4x-42=0";
        String[] parts = equation.split("x2|x|=");
// you will get 4 elements, but the last element is always 0
        for(int i=0; i<parts.length - 1; i++){
            System.out.println(varNames[i] + " = " + Integer.parseInt(parts[i]));
        }
    }
}

但在这种情况下,您将在输出中包含“+”符号。为避免这种情况,您可以使用Integer.parseInt(parts[i]) 而不是parts[i]

【讨论】:

    【解决方案4】:
    for ( int i = 0 ; i < str.length ; ++i ){
      if(asciiOf(str.charAt(i)) == asciiOfIntegerValue ){
        addCharInArrayList(str.charAt(i));
      }else{
          addInFuncList();
          addCharInArrayList("_");
      }
    
    
      // join numbers which are not separated by _ and apply BODMAS rule and solve it  
      // fyi : apologies - very inefficient pseudocode, wrote in a haste
    

    【讨论】:

      【解决方案5】:

      您可以按如下方式使用正则表达式:

      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 
      

      【讨论】:

      • 我得到的答案是 0 0 0
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-14
      • 2013-12-31
      • 1970-01-01
      相关资源
      最近更新 更多