Cannot make a static reference to the non-static field sc

Discussion in 'Mac Programming' started by soccersquirt82, Aug 21, 2008.

  1. soccersquirt82 macrumors 6502

    Joined:
    Mar 11, 2008
    #1
    I get the error, "Cannot make a static reference to the non-static field" about "Scanner sc = new Scanner (System.in);". If I put "static" in front of this line, three errors show stating, "The local variable f (or g/h) may not have been initialized." How do I fix this? I am trying to make three methods about functions and then putting them into a main program. I am using Java.

    {code}
    package attempt;
    import java.util.*;
    public class Methods2
    {

    // f(x) method
    static double f (double x) {
    return (6 * x - 3);
    }

    // g(x) method
    static double g(double x) {
    return (2*x*x - x - 1);
    }

    // h(x) method
    static double h (double x) {
    return (f(x) + g(x));
    }

    Scanner sc = new Scanner (System.in);

    public static void main(String[] args) {
    double f, g, h, x;

    //prints functions
    System.out.println("f(x) = 2x + 5");
    System.out.println("g(x) = 2x^2 - x - 1");
    System.out.println("h(x) = f(x) + g(x)");

    //user input
    System.out.print("x= ");
    x = sc.nextDouble();

    //answers
    System.out.println("f(x) = " + f);
    System.out.println("g(x) = " + g);
    System.out.println("h(x) = " + h);
    }
    }
    {code}
     
  2. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    Code tags are with square brackets [], not {}, and you need a /CODE at the end.

    sc must be static to be used in a static context, which it is (in public static void main). There's no need to declare variables f,g, and h in main, they are functions which the compiler will find and be able to get their type from the function definitions. There are some languages in which you must declare the type of a function in every context it is used, but Java is not one of them. x is the only double you need to declare in main.

    The other issue is you are not invoking the functions f,g, or h, you were just printing the (uninitialized) values of the variables you had defined in main. To call a function in java, you need to type it's name, an open parenthesis, then a comma separated list of arguments, then a closing parenthesis. In this case it would be something like:
    f(x)

    where f is the function you want to call, and x is the argument you want to pass it.

    As an aside it's probably best to declare and initialize sc in main, as it's not used in any other functions in the class. You should try to keep your variables in the lowest scope possible.

    -Lee

    P.S. What you print out as the equation for f(x) does not match what you defined in your function f. This causes some confusion when the program is run, as the results appear to be incorrect.
     
  3. soccersquirt82 thread starter macrumors 6502

    Joined:
    Mar 11, 2008
    #3
    Thanks so much!

    This is my updated one. I had to change some things from x to y, I put static in front of the scanner, and I tried to invoke functions.

    I get seven errors. Three for "f (g/h) cannot be resolved" on the last three lines, "Illegal modifier for parameter sc; only final is permitted" for static Scanner sc = new Scanner (System.in); "Syntax error on token ")" for f(x), delete this token, "Syntax error, insert ")" to complete Expression" for h(x, y), and "The method f(double) in the type Methods2 is not applicable for the arguments (double, double, double)" for f(x).

    I did not understand when you said f(x) does not match what you defined in your function f. I also didn't understand what you said about invoking functions, though I tried.

    Code:
    package attempt;
    import java.util.*;
    public class Methods2
    {
    	
    	// f(x) method
    	static double f (double x) {
    		return (6 * x - 3);
    		}
    
    	// g(x) method
    	static double g (double y) {
    		return (2*y*y - y - 1);
    		}
    	
    	// h(x) method
    	static double h (double x, double y) {
    		return (f(x) + g(y));
    		}	
    	
    	public static void main(String[] args) {
    		
    		double x, y;
    		f(x), g(y), h(x, y);
    		
    		static Scanner sc = new Scanner (System.in);
    		
    		//prints functions
    		System.out.println("f(x) = 2x + 5");
    		System.out.println("g(y) = 2y^2 - y - 1");
    		System.out.println("h(x) = f(x) + g(x)");
    		
    		//user input
    		System.out.print("x= ");
    		x = sc.nextDouble();
    		System.out.print("y= ");
    		x = sc.nextDouble();
    		
    		//answers
    		System.out.println("f(x) = " + f);
    		System.out.println("g(y) = " + g);
    		System.out.println("h(x) = " + h);
    	}
    }
    
    
    Thanks again!
     
  4. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #4
    OK, you're getting there... so now that you've moved sc into main, it does not need to be static, so you can just take that keyword off completely.

    Next... you don't need to do anything at all to declare functions. The only time you need to reference them in main are down in your last 3 lines... in those cases, you need to actually call the functions, not use their names.

    -Lee
     
  5. soccersquirt82 thread starter macrumors 6502

    Joined:
    Mar 11, 2008
    #5
    Thanks so much! Just three errors left and they all say, "f (g/h) cannot be resolved."

    Code:
    package attempt;
    import java.util.*;
    public class Methods2
    {
    	
    	// f(x) method
    	static double f (double x) {
    		return (6 * x - 3);
    		}
    
    	// g(x) method
    	static double g (double y) {
    		return (2*y*y - y - 1);
    		}
    	
    	// h(x) method
    	static double h (double x, double y) {
    		return (f(x) + g(y));
    		}	
    	
    	public static void main(String[] args) {
    		
    		double x, y;		
    		
    		Scanner sc = new Scanner (System.in);
    		
    		//prints functions
    		System.out.println("f(x) = 2x + 5");
    		System.out.println("g(y) = 2y^2 - y - 1");
    		System.out.println("h(x) = f(x) + g(x)");
    		
    		//user input
    		System.out.print("x= ");
    		x = sc.nextDouble();
    		System.out.print("y= ");
    		x = sc.nextDouble();
    		
    		//answers
    		System.out.println("f(x) = " + f);
    		System.out.println("g(y) = " + g);
    		System.out.println("h(x) = " + h);
    	}
    }
    
     
  6. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #6
    In the last three lines you have to call/invoke your methods. f on its own means nothing, how would you call f? You're already doing inside of g.

    -Lee
     
  7. soccersquirt82 thread starter macrumors 6502

    Joined:
    Mar 11, 2008
    #7
    Two errors: "The local variable y may not have been initialized" shown twice at + h(x, y)); + g(y));. Thanks so much for walking me through this.

    Code:
    package attempt;
    import java.util.*;
    public class Methods2
    {
    	
    	// f(x) method
    	static double f (double x) {
    		return (6 * x - 3);
    		}
    
    	// g(x) method
    	static double g (double y) {
    		return (2*y*y - y - 1);
    		}
    	
    	// h(x) method
    	static double h (double x, double y) {
    		return (f(x) + g(y));
    		}	
    	
    	public static void main(String[] args) {
    		
    		double x, y;		
    		
    		Scanner sc = new Scanner (System.in);
    		
    		//prints functions
    		System.out.println("f(x) = 2x + 5");
    		System.out.println("g(y) = 2y^2 - y - 1");
    		System.out.println("h(x) = f(x) + g(x)");
    		
    		//user input
    		System.out.print("x= ");
    		x = sc.nextDouble();
    		System.out.print("y= ");
    		x = sc.nextDouble();
    		
    		//answers
    		System.out.println("f(x) = " + f(x));
    		System.out.println("g(y) = " + g(y));
    		System.out.println("h(x) = " + h(x, y));
    	}
    }
    
     
  8. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #8
    I think you can figure this one out. You copied and pasted, but forgot to change something.

    -Lee
     
  9. soccersquirt82 thread starter macrumors 6502

    Joined:
    Mar 11, 2008
    #9
    It Works!!!!! Thank You So Much!!! :d:d:d:d:d
     
  10. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #10
    Still looks like you have the typo when you are printing what f(x) will do. It doesn't match the function definition.

    During the commercials I worked on implementing a little more dynamic version of h, with the ability to pass in the methods you want to compose to get the result. Most of this probably won't sense (and don't try to play with reflection yet), but I thought i'd post it for kicks:

    Code:
    import java.util.*;
    public class Methods2
    {
    
      // f(x) method
      static double f (double x) {
        return (6 * x - 3);
      }
    
      // g(x) method
      static double g(double x) {
        return (2*x*x - x - 1);
      }
    
      // h(x) method
      static double h (java.lang.reflect.Method a,java.lang.reflect.Method b,double x) throws IllegalArgumentException {
        double result = 0.;
        if(a.getReturnType() != double.class) throw new IllegalArgumentException("First functon does not return double");
        if(b.getReturnType() != double.class) throw new IllegalArgumentException("Second functon does not return double");
        Object[] aList = a.getParameterTypes();
        if(aList.length != 1 || aList[0] != double.class) throw new IllegalArgumentException("First function does not take a single double");
        Object[] bList = b.getParameterTypes();
        if(bList.length != 1 || bList[0] != double.class) throw new IllegalArgumentException("Second function does not take a single double");
        try {
          result = (((Double)a.invoke(new Methods2(),new Object[]{x})) + ((Double)b.invoke(new Methods2(),new Object[]{x})));
        } catch (Exception e) {
          throw new IllegalArgumentException("Methods could not be properly called");
        }
        return result;
      }
    
      static double h2 (Calcuable a, Calcuable b, double x) {
        return a.calc(x) + b.calc(x);
      }
      static double h3 (Calcuable a, Calcuable b, double x) {
        return a.calc(b.calc(x));
      }
    
    
      public static void main(String[] args) {
        double x;
        Scanner sc = new Scanner (System.in);
    
        //prints functions
        System.out.println("f(x) = 6x - 3");
        System.out.println("g(x) = 2x^2 - x - 1");
        System.out.println("h(x) = f(x) + g(x)");
    
        //user input
        System.out.print("x= ");
        x = sc.nextDouble();
     
        //answers
        System.out.println("f(x) = " + f(x));
        System.out.println("g(x) = " + g(x));
    
        java.lang.reflect.Method f;
        java.lang.reflect.Method g;
        try {
          f=Methods2.class.getDeclaredMethod("f",new Class[]{double.class});
          g=Methods2.class.getDeclaredMethod("g",new Class[]{double.class});
          System.out.println("h(x), f(x) + g(x) = " + h(f,g,x));
          System.out.println("h(x), f(x) + f(x) = " + h(f,f,x));
          System.out.println("h(x), g(x) + g(x) = " + h(g,g,x));
        } catch (NoSuchMethodException nsme) {
          System.err.println("Could not find methods!");
        } catch (SecurityException se) {
          System.err.println("Cannot access methods!");
        } catch (IllegalArgumentException iae) {
          System.err.println("Methods have incorrect signature or could not be executed. " + iae.toString());
        }
    
        System.out.println("h2(x), 2x + 5 + 5x - 2  = " + h2(new Calcuable () { public double calc(double x) { return 2*x + 5;}},
                                                            new Calcuable() { public double calc(double x) { return 5*x-2;}},x));
        System.out.println("h3(x), 2(5x - 2) + 5 = " + h3(new Calcuable () { public double calc(double x) { return 2*x + 5;}},
                                                            new Calcuable() { public double calc(double x) { return 5*x-2;}},x));
    
      }
    
      abstract static class Calcuable {
        public abstract double calc(double x);
      }
    }
    
     
  11. soccersquirt82 thread starter macrumors 6502

    Joined:
    Mar 11, 2008
    #11
    WOW! I fixed the f(x) println, and thanks again. Your new program is amazing!
     

Share This Page