我正在尝试创建的程序需要一些帮助。这是一个二次方程式,其中我有2个类。
我得到的唯一问题是代码
"QuadraticEquation Equation = new QuadraticEquation(a, b, c);"
我收到的错误是:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
No enclosing instance of type TestQuadraticEquation is accessible. Must qualify the allocation with an enclosing instance of type TestQuadraticEquation (e.g. x.new A() where x is an instance of TestQuadraticEquation).
at TestQuadraticEquation.main(TestQuadraticEquation.java:12)
此错误发生在第12行(上面的代码),我需要找出该部分的错误。
public class TestQuadraticEquation
{
public static void main (String [] args)
{
java.util.Scanner scan = new java.util.Scanner(System.in);
System.out.println("Please enter the coefficients a, b and c in the order: ");
double a = scan.nextDouble();
double b = scan.nextDouble();
double c = scan.nextDouble();
QuadraticEquation Equation = new QuadraticEquation(a, b, c);
if (Equation.getDiscriminant() > 0)
{
System.out.println("The roots of the equations are " + Equation.getRoot1()
+ " and " + Equation.getRoot2());
}
else
{
System.out.println("The equation has no roots.");
}
}
class QuadraticEquation
{
private double a;
private double b;
private double c;
QuadraticEquation()
{
a = 0;
b = 0;
c = 0;
}
QuadraticEquation (double newA, double newB, double newC)
{
a = newA;
b = newB;
c = newC;
}
public double getA()
{
return a;
}
public double getB()
{
return b;
}
public double getC ()
{
return c;
}
public double getDiscriminant()
{
return (Math.pow(b,2) - 4 * a * c);
}
public double getRoot1()
{
return ((-b + Math.sqrt(getDiscriminant())/(2 * a)));
}
public double getRoot2()
{
return ((-b - Math.sqrt(getDiscriminant())/(2 * a)));
}
}
}
答案 0 :(得分:0)
在这里,您尝试创建一个内部类的实例,即QuadraticEquation类。 QuadraticEquation类位于TestQuadraticEquation内部,因此,为了创建实例,您可以将QuadraticEquation声明为静态类,请参阅链接:problem creating object of inner class in java
其他选择是分离类,使QuadraticEquation.java和QuadraticEquation类的代码移动到那里。这样它就不再是内心阶级了。
另外,另一种选择就像编译器建议你创建TestQuadraticEquation的实例然后从那里你可以创建QuadraticEquation的新对象,可以通过以下方式完成:
QuadraticEquation Equation = new TestQuadraticEquation(). new QuadraticEquation(a, b, c);