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!
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.
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;
}
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.
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:");
}
}
}
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
}
}
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
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.
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.
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.
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;
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));
Bookmarks