www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 18

Thread: non-static method cannot be referenced from a static context

  1. #1
    Join Date
    Jan 2005
    Location
    Los Angeles, California
    Posts
    18

    Exclamation non-static method cannot be referenced from a static context

    Alright dudes. I'm a newbie at Java, so please bear with me. I'm pretty much an intermediate ace at C++ and JavaScript (since they're so similar) by now, but Java is one of those languages I just don't get. I'm sure newbies like me come up with this error all the time, but I've looked everywhere (both online and in The Java Tutorial, Third Edition) for why I get it, and I don't really get any of the answers. So if someone would please be kind enough to explain it to me piece by piece (as if I'm a little kid), I'd really appreciate it. Use C++ analogies if you can. Thanks a whole lot. ^_^"

    The compiler error output:

    Code:
    C:\My Documents\Pic20aSchedule.java:8: non-static variable currentDate cannot be
     referenced from a static context
                    currentDate = now.toString();
                    ^
    C:\My Documents\Pic20aSchedule.java:9: non-static variable currentTime cannot be
     referenced from a static context
                    currentTime = " [The time is not yet initialized.]";
                    ^
    C:\My Documents\Pic20aSchedule.java:10: non-static method printSchedule() cannot
     be referenced from a static context
                    printSchedule();
                    ^
    3 errors


    The code (Pic20aSchedule.java):

    Code:
    import java.util.*;
    import java.text.DateFormat;
    
    class Pic20aSchedule extends Object {
    	
    	public static void main(String[] args) {
    		Calendar now = Calendar.getInstance();
    		currentDate = now.toString();
    		currentTime = " [The time is not yet initialized.]";
    		printSchedule();
    	}
    	
    	public void printSchedule() {
    
    		System.out.println("The current date and time is " + currentDate + " at " + currentTime + ".");
    	}
    	
    	public String currentDate;
    	public String currentTime;
    	public String nextSession;
    	
    }
    As some of you may have guessed, this is actually a homework assignment, and it is far from complete. I know this place isn't a tutoring joint, but I don't know of anywhere else to turn but the kind WebDeveloper.comers out there. ^_^" If it helps, here is the site where the assignment is located: http://www.math.ucla.edu/~yan/20a.1..../project1.html.

    Thank you GREATLY to anyone that can help me out. I have a midterm today and I really need to understand this. íMuchas gracias!

  2. #2
    Join Date
    Jan 2004
    Location
    Melbourne, Australia
    Posts
    5,298
    The main method is static, which means it cannot referance non-static variables or methods (functions in C++).

    Change your code so it looks like this:
    Code:
    import java.util.*;
    import java.text.DateFormat;
    
    class Pic20aSchedule extends Object 
    {
    	public static void main(String[] args) {
                             new Pic20aSchedule();
    	}
    
                 public Pic20aSchedule()
                 {
    		Calendar now = Calendar.getInstance();
    		currentDate = now.toString();
    		currentTime = " [The time is not yet initialized.]";
    		printSchedule();
                 }
    	
    	public void printSchedule() {
    
    		System.out.println("The current date and time is " + currentDate + " at " + currentTime + ".");
    	}
    	
    	private String currentDate;
    	private String currentTime;
    	private String nextSession;
    }
    All I have done is included a constructor, which is simply a method that is called when an instance of this object is created.

    I also made your instance variables private instead of public. This is a convention that I suggest you follow.

    Regards.

  3. #3
    Join Date
    Jan 2005
    Location
    Los Angeles, California
    Posts
    18
    Hmm... Whoa! Thanks a lot! That seemed to have fixed all the compiler errors. But now I get the following runtime error:

    Code:
    Exception in thread "main" java.lang.NoClassDefFoundError: C:\My Documents\Pic20
    aSchedule/class
    Here's my code, just in case I made a code typo:

    Code:
    import java.util.*;
    import java.text.DateFormat;
    
    class Pic20aSchedule extends Object {
    	
    	public static void main(String[] args) {
    		new Pic20aSchedule();
    	}
    	
    	public Pic20aSchedule() {
    		Calendar now = Calendar.getInstance();
    		currentDate = now.toString();
    		currentTime = " [The time is not yet initialized.]";
    		printSchedule();
    	}
    	
    	public void printSchedule() {
    
    		System.out.println("The current date and time is " + currentDate + " at " + currentTime + ".");
    	}
    	
    	private String currentDate;
    	private String currentTime;
    	//private String nextSession;
    	
    }
    Any ideas?

  4. #4
    Join Date
    Jan 2004
    Location
    Melbourne, Australia
    Posts
    5,298
    This can mean a number of things. I believe it normally means that Java cannot find the class file. Have you set your classpath? Read this article, which explains the classpath variable.

    Regards.

  5. #5
    Join Date
    Jan 2005
    Location
    Los Angeles, California
    Posts
    18
    Haha, whoa. Thanks a lot. As it turns out, I was typing out the ".class" extension with the class name when I used the "java" command line.

    (java Pic20aSchedule.class)

    Who knew we weren't supposed to do that? ^_^"

    For all you newbies out there (like me), the correct command line in Windows is java yourClassName with no .class at the end. ^_^

    Thanks a lot for your help BUNTINE. Happy moderatin'. ^_^"

  6. #6
    Join Date
    Jan 2004
    Location
    Melbourne, Australia
    Posts
    5,298
    Cheers. That gets alot of beginners.

  7. #7
    Join Date
    Jun 2005
    Location
    Chicago.
    Posts
    60

    Red face I still have a problem.

    Hi everyone,

    I had the same Error message" non-static method read() cannot be referenced from a static context " when I was trying to write this very first program in java. I am so green when it comes to java. I appreciate any help.

    Code:
    public class CrapsGame
    {   
        public static void main(String[] args)
        {
           new CrapsGame();
         }
         public CrapsGame()
         {
            // instance variables 
            char choice;
            choice=Reader.read();
            // main body
            switch(choice)
            {
                case '1':
                System.out.println("What is the money limit you want to put in this game? money:");
                case '2':
                System.out.println("What is the money limit you want to put in this game? money:");
                default:
                System.out.println("What is the money limit you want to put in this game? money:");
            }
         }
    }
    Thanks for any suggestions

  8. #8
    Join Date
    Oct 2004
    Posts
    1,118
    Thanks for any suggestions
    You are in way over your head. Get a beginning java book like "Java 2: A Beginner's Guide" (Herbert Schildt), and read it and do the exercises.

    You have to learn the difference between a static and a normal method. A static method exists before any objects of the class are created, and it is called like this:

    ClassName.methodName();

    A regular method only exists after an object of the class is created, and it is called like this:

    ClassName myObj = new ClassName();
    myObj.methodName();

    In your program, you are calling the CrapsGame() method from inside the static method main(). However, from the rules above, the method CrapsGame() does not exist yet. Note: you can call a static method from inside a regular method.

    Here are some suggestions:

    1) Do not name the method you are creating, i.e. CrapsGame() the same name as your class.

    2) Declare your method as static and that way it will exist before any objects of the class exist and therefore you can call it from other static methods like main().

    3) You might want to try and organize beginning programs like this:
    Code:
    class Apple  //do not declare this class public, otherwise it will need to be in it's own file
    {
            private String color; 
    		
    	public Apple(String aColor) //constructor
    	{
    		color = aColor;
    	}
    
    	public void show() //a regular method
    	{
    		System.out.println("The apple's color is: " + color);
    	}
    }
    
    public class DemoApple //this program must be in a file named DemoApple
    {
    	public static void main(String[] args) //program execution begins here
    	{
    		Apple myApple = new Apple("red");  //create Apple object
    		myApple.show();  //call regular Apple method
    	}
    }
    Last edited by 7stud; 06-08-2005 at 09:01 PM.

  9. #9
    Join Date
    Jun 2005
    Location
    Chicago.
    Posts
    60

    Thank you very much brother.

    Thanks a lot Brother, I am gonna buy the book you recommended to me. About Static and nonstatic, I did read about them today. I tried what you suggested but for some reason it is giving me the same error.

    I will try harder and I will let you know. Thanks again

  10. #10
    Join Date
    Oct 2004
    Posts
    1,118
    About Static and nonstatic, I did read about them today. I tried what you suggested but for some reason it is giving me the same error.
    Post your code.

  11. #11
    Join Date
    Jun 2005
    Location
    Chicago.
    Posts
    60
    Code:
    import java.io.*;
    
    public class CrapsGame
    {   
        public static void main(String[] args)
            //thows IO IOException
        {
            // instance variables 
            //InputStreamReader stdin =
    	//			new InputStreamReader(System.in);
    	//	BufferedReader console =
    	//			new BufferedReader(stdin);
    
            //choice = console.readLine();
            String choice= Reader.read(); // I get the error messsage here
           // main body
         }
    }
    NOTE: I put some other solution up there in the code that worked "didn't give me any syntax or logic error messaage", but it gave me a run time problem, where the compiler didn't stop executing the program, and I didn't get anythinig, not even the console window.



    I tried to creat another class such as

    Code:
    class Cin
    {
         public char value()
         {
               return Reader.read();
         }
    }
    and then in the main method I wrote:
    Code:
    Cin enter = new Cin();
    char choice = enter.value();  // I got the error message here.
    Please I appreciate any help.

  12. #12
    Join Date
    Oct 2004
    Posts
    1,118
    String choice= Reader.read(); // I get the error messsage here
    What is Reader.read()? From whence do you think you are reading?

    There is a class called Reader that is an abstract base class for all the character input streams in Java. The Reader class implements several versions of a method called read(). Your code is saying there is a version of the read() method that is static. How do I know that? Because you are calling a method with a class name instead of an object name, and static methods are called with the class name while regular methods are called with an object name. Unfortunately for you, there is no static version of read() in the Reader class, so it will take a lot more work to read in data from whatever source you are trying to obtain input.

    Input and output in Java is one of the most convoluted and confusing topics I've ever experienced in programming. It will be tough to wing it. Good luck.
    Last edited by 7stud; 06-09-2005 at 04:11 AM.

  13. #13
    Join Date
    Jun 2005
    Location
    Chicago.
    Posts
    60

    Thumbs up Wow, Thanks bro...

    Yes, writing and reading in java IS confusing, but I am learning little by little. I will read more about this topic and I am gonna try to code more, so I understand it better. I now know what the error is. You are absolutely correct. I really appreciate your responses on my questions, and I wish you the best brother.


  14. #14
    Join Date
    Sep 2007
    Posts
    2

    similar issues

    gang, I am having similar issues in my coding project. I tried to follow the suggestions in this forum, but being a newbie myself I obviously screwed something up. I am trying to access the methods in another file, but I am getting the same errors of trying to access non-static methods from static context. If someone could please help me to figure this out, I would be incredibly grateful for the help. I will be adapting this menu interface for several projects to come, and I am getting desperate for direct help. thanks


    import java.util.Scanner;

    class Assign3Driver
    {
    static Scanner scan = new Scanner(System.in);

    public static void main(String[] args)
    { new Assign3Driver();
    }


    public void Assign3Driver()
    {
    int userChoice = 0;
    while (userChoice != 12)
    {
    menu();
    userChoice = scan.nextInt();
    menuSwitch(userChoice);
    }
    }

    public void menuSwitch(int choice)
    {

    int loc;
    switch(choice)
    {
    case 1:
    System.out.println("REMOVING FIRST: ");
    SortableList.removeFirst();
    break;

    case 2:
    System.out.println("REMOVING LAST: ");
    SortableList.removeLast();
    break;

    case 3:
    System.out.println("REMOVE WHAT? ");
    int Cut = scan.nextInt();//change scan type
    SortableList.remove(Cut);
    break;


    case 4:
    System.out.println("SEE FIRST: ");
    SortableList.first();
    break;

    case 5:
    System.out.println("SEE LAST: ");
    SortableList.last();
    break;

    case 6:
    System.out.println("SEARCH FOR WHAT? ");
    int Look= scan.nextInt();//change scan type
    SortableList.contains(Look);
    break;

    case 7:
    System.out.println("VIEW SIZE");
    SortableList.size();
    break;

    case 8:
    System.out.println("VIEW LIST AS STRING");
    SortableList.toString();
    break;

    case 9:
    System.out.println("sort by what");
    int sort=scan.nextInt();//change scan type
    //SortableList.sort(sort); not yet usable
    break;

    case 10:
    System.out.println("REVERSE STRING");
    //SortableList.reverseString(); not yet usable
    break;

    case 11:
    System.out.println("SELECT WHAT BASED ON WHAT?");
    int k=scan.nextInt();
    int c=scan.nextInt();//change scan type
    //SortableList.select(); not yet usable
    break;

    case 12:
    System.out.println("EXITING");
    break;

    default:
    System.out.println("Sorry, invalid choice");
    }
    }

    public void menu()
    {
    System.out.println("\nDriver Menu ");
    System.out.println("*************");
    System.out.println("1: remove first");
    System.out.println("2: Remove last");
    System.out.println("3: remove target");
    System.out.println("4: see first");
    System.out.println("5: see last");
    System.out.println("6: Search for element");
    System.out.println("7: view size");
    System.out.println("8: string list");
    System.out.println("9: sort");
    System.out.println("10: reverse string");
    System.out.println("11: select element");
    System.out.println("12: exit");
    System.out.print("\nEnter your choice: ");
    }
    }

  15. #15
    Join Date
    Feb 2012
    Posts
    1

    having same problem :S

    Below is a piece of a code i'm working on, any idea why it's giving me a 'non-static variable this cannot be referenced from a static context' error? It's in the last line of the code. Help would be greatly appreciated!


    public static void addPatient(List<Patient> patientListIn)
    {
    Scanner scan = new Scanner(System.in);
    String name;
    String surname;
    int phoneNumber;
    int patientID;

    System.out.print("Please enter patient name: ");
    name = scan.nextLine();
    System.out.print("Please enter patient surname: ");
    surname = scan.nextLine();
    System.out.print("Please enter patient phone number: ");
    phoneNumber = scan.nextInt();
    System.out.print("Please enter patient ID: ");
    patientID = scan.nextInt();
    patientListIn.add(new Patient(name, surname, phoneNumber, patientID));

    }

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles