+ 2
error: non-static variable introduction cannot be referenced from a static context!
Hey everyone, I tried to code using what I learned from "Arrays", "Loops" and "Methods". However, I was not quite successful. I left the link below. Please help me with debugging it. https://code.sololearn.com/cbGrgC6VF2w1/#java Thanks.
3 odpowiedzi
+ 2
When you want to access the field that are not static you must create an object, then use that object to reference the field (except private) that you want to use. Or when creation of object is not needed declare the field as static
+ 3
Reza Please check this .. it will help
class MyClass {
// you need to make static introduction variable because you are using this variable in static method
static String[ ] introduction = { "My", "name", "is", "Reza"};
static void sayHello(int x) {
System.out.println(introduction[x]);
}
public static void main(String[] args) {
// and here x = 0 , because the array start with 0th index
for(int x = 0; x <=3; x++) {
// add here you can just variable while calling
sayHello(x);
}
}
}
0
Java main() method cannot access a non-static member of its class. That means, public static void main(String[] args) is a static method. Instance variables (variables defined in the class but not marked as static keyword) cannot be accessed from a static method without referencing an instance of the class. An attempt to use the variables and methods of the class which do not have the static modifier without creating an instance of the class is caught by the Java compiler at compile time and flagged as an error: Cannot Be Referenced From a Static Context . To solve your problem, you need to create an instance of your class and then you can access the methods and variables of the class that have not been declared with the static modifier .
Static methods are useful if you have only one instance where you're going to use the method, and you don't need multiple copies (objects). Non-static methods are used if you're going to use your method to create multiple copies.
http://net-informations.com/java/err/static.htm