Click here to Skip to main content
15,888,733 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
class Book
{
    //// FIELDS ////
    private String longestWord;
    private int wordCount;
    private ArrayList<String> wordList = new ArrayList<String>();
    /* Declare fields for the word list, the word count, and the longest word.*/
    
    ////// CONSTRUCTOR //////
    //@param f -- the file object
    public Book(File f)
    {
        wordList = readBook(f);
        wordCount = countWords(wordList);
        longestWord = findLongestWord(wordList); 
    }

public static String findLongestWord(ArrayList<String> b)
    {
        try 
        {
            String longest = b.get(0);
        }
        catch (Exception f)
        {
            System.out.println("The longest word eludes me.");
        }
        return longestWord; //Error: non-static variable longestWord cannot be referenced from a static context//
    }


What I have tried:

I've made sure all the case-sensitive things are squared away, but It truly have no idea how to fix it!
Posted
Updated 16-Apr-20 10:16am

1 solution

Your findLongestWord method is declared as static which means that it isn't associated with any particular instance of the containing class. This means that you don't specify an instance when you call it, you just refer to the class.
Think about cars for a moment: You can ask "how many wheels has a car?" without needing to specify your car, or my car - because all cars have four wheels (if they had two, they would be motorcycles). But if you want to ask about colour, you have to say which car you mean - because all cars are not the same colour, you have to specify the instance: "What colour is your car?", "what colour is my car?", or "what colour is that car, the one over there beside the red one?"

Java is the same: for a static method, you "ask static questions" - and that means that just like cars, you can't access instance related information in a static method / question as there isn't one to talk about!

Either change longestWord to also be static (probably what you want) or change findLongestWord to be non static.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900