Question

Can anyone find why this is this class wont run? I've made some error or another, but I can't seem to see the error. I instantiate an object and print what should be its area using what I believe is the proper notation to return the value I desire. The information in the object should evaluate to ~7.2.

public class TrapApx
{
    private double x1;
    private double x2;
    private double distance;
    private double numberOfSections;
    private double changeInX;
    private double area = 0;

    public TrapApx(double firstX, double secondX, double numOfSec)
    {
        x1 = firstX;
        x2 = secondX;
        numberOfSections = numOfSec;
    }

    public double distance()
    {
        return distance = x2 - x1;
    }

    public double changeX()
    {
        return changeInX = distance / numberOfSections;
    }

    public double funcX(double x)
    {
        return Math.sqrt(x-1);
    }

    public double areaApx()
    {
        for(double x = x1; x < x2; x += changeInX)
        {
            area += (funcX(x) + funcX(x + changeInX))/2 * changeInX;
        }
        return area;
    }
}

public class TrapApxTest
{
    public static void main(String []args)
    {
        TrapApx one = new TrapApx(1, 6, 5);
        System.out.println(one.areaApx());
    }
}

and I tried to see if something was not functioning with one of my variables or their mutations, so I created this static class with no objects and tested it procedurally, and it returned the proper answer.

public class tester
{
    public static double funcX(double x)
    {
        return Math.sqrt(x-1);
    }

    public static void main(String []args)
    {
        double x1 = 1,
               x2 = 6,
               distance = x2 - x1,
               numberOfSections = 5,
               changeInX = distance / numberOfSections,
               area = 0;

        for(double x = x1; x < x2; x += changeInX)
        {
            area += (funcX(x) + funcX(x + changeInX))/2 * changeInX;
        }

        System.out.println(area);
    }
}

Thanks for the help, guys.

Was it helpful?

Solution

The problem is that you never run the distance() method, so the distance field stays at zero. It's a really terrible idea to give a field and a method the same name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top