gpt4 book ai didi

java - int 无法解析为变量 java

转载 作者:行者123 更新时间:2023-12-01 22:21:20 26 4
gpt4 key购买 nike

问题:当我尝试将 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;

}

最佳答案

如果您希望 a1b1c1 在 if 语句 block 之前声明它们仍然位于该 block 之后的范围内结束。

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;

关于java - int 无法解析为变量 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29721402/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com