bob9123
bob9123

Reputation: 745

Using toString() with Arrays Java -New programmer

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

Answers (3)

JaskeyLam
JaskeyLam

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:

  1. make your array static:

    private static String[] words = ...//make it static

or

  1. create an instance before you get access to it:

    System.out.println(new Freddy());//This will call it'stoString()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

Antony Dao
Antony Dao

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

user2575725
user2575725

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

Related Questions