int无法解析为变量java

时间:2015-04-18 18:47:51

标签: java android string

问题:当我试图将int转换为double时,它会显示int无法解析为变量的错误。该程序将输入二次方程作为输入,并以此格式提取aX2-bX-c = 0的系数,并求解二次方程。但是从int转换为double是一个错误。

计划:

  public static String quad (final String equation)
  {
  final String regex = "([+-]?\\d+)X2([+-]\\d+)X([+-]\\d+)=0";
  Pattern pattern = Pattern.compile(regex);


  Matcher matcher = pattern.matcher(equation);

  if (matcher.matches()) {
      int a1 = Integer.parseInt(matcher.group(1));
      int b1 = Integer.parseInt(matcher.group(2));
      int c1 = Integer.parseInt(matcher.group(3));

     // System.out.println("a=" + a + "; b=" + b + "; c=" + c);
  } 
  double a = (double) a1; // error message a1 cannot resolve into variable
  double b = (double) b1; // error message b1 cannot resolve into variable
  double c = (double) c1; // error message c1 cannot resolve into variable


    double r1 = 0;
    double r2 = 0;
    double discriminant = b * b - 4 * a * c;
    if (discriminant > 0){

        // r = -b / 2 * a;

        r1 = (-b + Math.sqrt(discriminant)) / (2 * a);
        r2 = (-b - Math.sqrt(discriminant)) / (2 * a);

    //  System.out.println("Real roots " + r1 + " and " + r2);
    }
    if (discriminant == 0){
        // System.out.println("One root " +r1);

        r1 = -b / (2 * a);
        r2 = -b / (2 * a);

    }
    if (discriminant < 0){
    //  System.out.println(" no real root");

    }

    String t1 = String.valueOf(r1);
    String t2 = String.valueOf(r2);
    String t3 ;
    t3 = t1+" "+t2;
    return t3;

 }

2 个答案:

答案 0 :(得分:3)

如果您希望在该块结束后仍然在范围内,则必须在if语句块之前声明a1b1c1

int a1 = 0;
int b1 = 0;
int c1 = 0;
if (matcher.matches()) {
    a1 = Integer.parseInt(matcher.group(1));
    b1 = Integer.parseInt(matcher.group(2));
    c1 = Integer.parseInt(matcher.group(3));
    // System.out.println("a=" + a + "; b=" + b + "; c=" + c);
} 
double a = (double) a1; 
double b = (double) b1; 
double c = (double) c1; 

答案 1 :(得分:0)

您可以直接使用双打:

double a = 0.0, b = 0.0, c = 0.0;
if (matcher.matches()) {
    a = Double.parseDouble(matcher.group(1));
    b = Double.parseDouble(matcher.group(2));
    c = Double.parseDouble(matcher.group(3));
}