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