0

So, Im trying to learn JAVA by myself and have come across the infamous "non-static variable this cannot be referenced from a static context" error.

I know its a repeat for you guys, but I dont understand why its happening...

public class JavaApplication1 {

public static void main(String[] args) {
    /** Error comes from line below */
    Anagram Pay = new Anagram(3,"PAYPAL");
    System.out.println(Pay.horzArray);
}

public class Anagram{
private int vertArray;    
private int horzArray; 
private String starterWord;
private int wordLength;
private int diagonalMax;

public Anagram(int verticalArray, String inputWord){
vertArray = verticalArray;
starterWord = inputWord;
wordLength = starterWord.length();
if (vertArray > 2)
      diagonalMax = vertArray - 2;
else
      diagonalMax = 0;

horzArray = wordReducer(wordLength);
}

public int wordReducer(int word){
int step = 1;
int horzValue = 0;
while (word > 0)
if (step == 1) {
    word = word - vertArray;
    step = step + 1;
    horzValue = horzValue + 1;
} else {
  word = word - diagonalMax;
  step = 1;
  horzValue = horzValue + diagonalMax;
}
return horzValue;
}
        }
};

(P.S If anyone is curious - Im in the process of answering this: https://leetcode.com/problems/zigzag-conversion/description/ )

  • is your `Anagram` class in the same file as your `JavaApplication1`? – luk2302 Oct 01 '17 at 10:55
  • Indent your code, and post the exact and complete error message you get., alongwith the relevant code. – JB Nizet Oct 01 '17 at 10:57
  • `Anagram` is an inner class of `JavaApplication1`: you need an instance of the latter to create the former. The easiest thing to do is to put `Anagram` inside its own file; or declare the class `static`. – Andy Turner Oct 01 '17 at 10:57
  • Thanks guys. I moved Anagram to its own file and alls good with the world :) – CubicleDrone7 Oct 01 '17 at 11:11

0 Answers0