我要创建的程序需要一些帮助。这是一个二次方程式,其中我有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)));
}
}
}
最佳答案
在这里,您尝试创建一个内部类的实例,该内部类是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);