0

problem : when i'm trying to convert int into double it's showing an error that int cannot resolve into variable . This program will input quadratic equation as input and extracts the coefficient of aX2-bX-c=0 in this format and solve the quadratic equation. But it is some error in conversion from int to double.

Program :

  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;

 }
0

2 Answers 2

3

You must declare a1,b1 and c1 prior to the if statement block if you want them to still be in scope after that block ends.

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; 
Sign up to request clarification or add additional context in comments.

Comments

0

You can use directly doubles:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.