Reputation: 745
My goal is to print out all the words in the array and make sure they are in a string.( In order). So far I'm at:
public class Freddy {
private String[] words = new String[]{"Hello", "name", "is", "Bob"};
public String toString() {
for (int i = 0; i <words.length; i++)
System.out.println(words[i]);
return null;
}
public static void main(String[] args) {
System.out.println();//Not sure not to print out here. When I say print(words) it gives error "Error:(16, 24) java: non-static variable words cannot be referenced from a static context"
}
}
Thanks!
Upvotes: 0
Views: 237
Reputation: 15755
You error is because you are trying to access to instance variable in static method(main) without creating the instance.
To fix your error:
make your array static:
private static String[] words = ...//make it static
or
create an instance before you get access to it:
System.out.println(new Freddy());//This will call it's
toString()method.
In order to convert an array to String, use Arrays#toString is a better way:
public String toString() {
return Arrays.toString(words);//Convert the array into string, toString returns null is a bad habbit.
}
Check How to convert an int array to String with toString method in Java for more details
Upvotes: 2
Reputation: 425
A static
method can only use static
fields from class.
Your main()
method is static
, then your method toString()
and array String[] words
must be static
too.
However, in your case, you should follow the way that @Arvind show.
Upvotes: 1
Reputation:
Problem is main() is static, whereas words is an instance variable, meaning it cannot exist without the instance of Freddy.
Simply pass the instance of class:
System.out.println(new Freddy());
Upvotes: 0