This may happen too if you are accessing non-static members from the static methods or likewise.
Following are two different aspects, one which cause the error and other solved piece of code.
it's just the matter of making other as class "static"
package Stack;
import java.util.Stack;
import java.util.*;
public class StackArrList {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Stack S = new Stack();
System.out.println("Enter some integers and keep 0 at last:\n");
int n = in.nextInt();
while (n != 0) {
S.push(n);
n = in.nextInt();
}
System.out.println("Numbers in reverse order:\n");
while (!S.empty()) {
System.out.printf("%d", S.pop());
System.out.println("\n");
}
}
public class Stack {
final static int MaxStack = 100;
final static int Value = -999999;
int top = -1;
int[] ST = new int[MaxStack];
public boolean empty() {
return top == -1;
}
public int pop() {
if (this.empty()) {
return Value;
}
int hold = ST[top];
top--;
return hold;
}
public void push(int n) {
if (top == MaxStack - 1) {
System.out.println("\n Stack Overflow\n");
System.exit(1);
}
top++;
ST[top] = n;
}
}
}
This throws the error No enclosing instance of type StackArrList is accessible. Must qualify the allocation with an enclosing instance of type StackArrList (e.g. x.new A() where x is an instance of StackArrList). and will not allow to make instance of Stack class
When you make the class Stack to static class Stack will work fine and no error will be there.
package Stack;
import java.util.Stack;
import java.util.*;
public class StackArrList {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Stack S = new Stack();
System.out.println("Enter some integers and keep 0 at last:\n");
int n = in.nextInt();
while (n != 0) {
S.push(n);
n = in.nextInt();
}
System.out.println("Numbers in reverse order:\n");
while (!S.empty()) {
System.out.printf("%d", S.pop());
System.out.println("\n");
}
}
static class Stack {
final static int MaxStack = 100;
final static int Value = -999999;
int top = -1;
int[] ST = new int[MaxStack];
public boolean empty() {
return top == -1;
}
public int pop() {
if (this.empty()) {
return Value;
}
int hold = ST[top];
top--;
return hold;
}
public void push(int n) {
if (top == MaxStack - 1) {
System.out.println("\n Stack Overflow\n");
System.exit(1);
}
top++;
ST[top] = n;
}
}
}