-2

Okay, I am trying write the function y = c + bx + cx^2 in java with the capability of calling it the main method. This is what I have so far:

public double poly(double c, double b, double a, double x)
{ 
    y = c + b*x + a*x*x;    
    return y;
}       

and here is what I type in the main method:

public static void main(String[] args)
{
    System.out.println(poly(2,2,2,2));
}

The error I get is

non-static method poly(double,double,double,double) cannot be referenced from a static context.

How can I fix this? I am just trying to evaluate the function and print out the result.

pkamb
  • 33,281
  • 23
  • 160
  • 191
noName
  • 3
  • 1
  • 2

1 Answers1

0

Just add static to the method!

public static double poly(double c, double b, double a, double x)
{ 
    y = c + b*x + a*x*x;    
    return y;
}

The static keyword in Java means that the variable or function is shared between all instances of that class as it belongs to the type, not the actual objects themselves. So if you have a variable: private static int i = 0; and you increment it ( i++ ) in one instance, the change will be reflected in all instances.


EDIT: SOLUTION

public class sample {

    public static void main(String[] args) {
        System.out.println(poly(2, 2, 2, 2));
    }

    public static double poly(double c, double b, double a, double x) {
        double y = c + b * x + a * x * x;
        return y;
    }
}

Output: 14

codeCompiler77
  • 508
  • 7
  • 22
  • I added that, and when I ran the code I was met with the message "non-static variable y cannot be referenced from a static context." – noName Feb 28 '16 at 18:41
  • @noName that means you didn't add it. It's telling you that you're missing the `static`, look at my post again. – codeCompiler77 Feb 28 '16 at 18:49