【问题标题】:int Cannot resolve into a variable javaint 无法解析成变量 java
【发布时间】:2015-04-18 18:47:51
【问题描述】:

问题:当我尝试将 int 转换为 double 时,它​​显示 int 无法解析为 variable 的错误。该程序将输入二次方程作为输入,并以这种格式提取 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;

 }

【问题讨论】:

    标签: java android string


    【解决方案1】:

    您必须在 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; 
    

    【讨论】:

      【解决方案2】:

      你可以直接使用双打:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-15
        • 2016-05-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多