Isso também pode acontecer se você estiver acessando membros não estáticos a partir de métodos estáticos ou da mesma forma. A seguir estão dois aspectos diferentes, um que causa o erro e outro que é resolvido. é apenas uma questão de fazer outra classe "estática"
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;
}
}
}
Isso gera o erro Nenhuma instância envolvente do tipo StackArrList está acessível. Deve qualificar a alocação com uma instância envolvente do tipo StackArrList (por exemplo ,xnew A () onde x é uma instância de StackArrList). e não permitirá fazer instância da classe Stack
Quando você transformar a classe Stack em uma classe estática, a Stack funcionará bem e nenhum erro ocorrerá.
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;
}
}
}