Reputation: 805
I'll preface this by saying that I've been a longtime fan of Stack Overflow, and over the past few semesters I've usually been able to find the answer to all my questions without actually asking one. However, I've been having problems with a stack program. There's more code than this, but I think I've narrowed my problem down to this one error. It states
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Cannot make a static reference to the non-static field Stack1
The constructor Stack(int) is undefinedat stack.main(stack.java:11)
Can anyone explain what the issue might be? Or better yet, point me to somewhere that will explain it? I've tried looking it up on Overflow and through google, but I think a combination of not knowing what I'm actually looking for and/or fatigue is preventing me from finding a concrete answer. Thanks for any help in advance.
public class stack {
private Object[] Stack1;
private int topOfStack;
private int max;
//private int empty;
//private int capacity;
public static void main(String[] args) {
Stack1 = new Stack(5);
}
public Stack(int size) {
if (size < 0){
throw new IllegalArgumentException("Parameter must be >0. Parameter was " + size + ".");
}
max = size;
Stack1 = (Object[]) (new Object[size]);
topOfStack = -1;
}
}
Upvotes: 2
Views: 3768
Reputation: 6608
Stack1
is in instance variable to the stack
class. In your static main method, you try to store a value in the Stack1
variable even though it is an instance variable. Also, you try to assign a non-array type to a variable whose type is an array of Object
. Furthermore, you have a constructor for Stack
(note the uppercase) even though the class is called stack
in lowercase.
Upvotes: 0
Reputation: 51030
In the following line -
private Object[] Stack1;
Stack1
is not static.
And in the following you are trying to refer to Stack1
-
public static void main(String[] args) {
Stack1 = new Stack(5);
}
from within main
which is static.
Thus -
Cannot make a static reference to the non-static field Stack1
Your constructor name is Stack
which does not match class name is stack
. So -
The constructor Stack(int) is undefined
May be, you want to name your class Stack
and in your main
the following -
public static void main(String[] args) {
Stack stack1 = new Stack(5);
}
Upvotes: 1
Reputation: 5518
Rename your class "Stack" (uppercase) and change the line:
Stack1 = new Stack(5)
to:
Stack stack1 = new Stack(5);
Upvotes: 1
Reputation: 11238
Keeping the lower case class declaration, I'm guessing the assignment
Stack1 = new Stack(5);
is not what you meant. Rather:
Stack1 stack = new stack(5);
Upvotes: 0