我的目标是打印出数组中的所有单词,并确保它们是一个字符串。(按顺序)。 到目前为止,我在:
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"
}
}
谢谢!
答案 0 :(得分:2)
您的错误是因为您尝试在静态方法(main)中访问实例变量而不创建实例。
修复错误:
使您的数组静态:
private static String[] words = ...//make it static
或
在您访问它之前创建一个实例:
System.out.println(new Freddy());//This will call it's
的toString()method.
要将数组转换为字符串,请使用Arrays#toString是更好的方法:
public String toString() {
return Arrays.toString(words);//Convert the array into string, toString returns null is a bad habbit.
}
查看How to convert an int array to String with toString method in Java了解详情
答案 1 :(得分:1)
static
方法只能使用课程中的static
个字段。
您的main()
方法为static
,那么您的方法toString()
和数组String[] words
也必须为static
。
但是,在您的情况下,您应该遵循@Arvind显示的方式。
答案 2 :(得分:0)
问题是main()是静态的,而words是一个实例变量,这意味着没有Freddy的实例它就不存在。
只需传递class的实例:
System.out.println(new Freddy());