Esto también puede suceder si accede a miembros no estáticos desde los métodos estáticos o de manera similar. A continuación se presentan dos aspectos diferentes, uno que causa el error y otro fragmento de código resuelto. es solo cuestión de hacer "estático" a otro
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;
}
}
}
Esto arroja el error No se puede acceder a ninguna instancia adjunta del tipo StackArrList. Debe calificar la asignación con una instancia adjunta de tipo StackArrList (por ejemplo, xnew A () donde x es una instancia de StackArrList). y no permitirá hacer una instancia de la clase Stack
Cuando haga la clase Stack en clase estática, Stack funcionará bien y no habrá ningún error.
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;
}
}
}