问题遇到的现象和发生背景
在main method中,用构造器创建new ArrayQueue时报错。
non-static variable this cannot be referenced from a static context
问题相关代码,请勿粘贴截图
import java.util.Scanner;
public class ArrayQueueDemo{
public class ArrayQueue{
int max_size ;
int front ;
int rear ;
int[] queue;
// construstor for the Arrayqueue
public ArrayQueue(int size){
max_size = size;
front = -1;
rear = -1;
queue = new int[size];
}
// check if it is full
public boolean isFull(){
return rear == max_size - 1;
}
// check if it is empty
public boolean isEmpty(){
return front == rear;
}
// adding items to the queue
public void addQueue(int num){
if(isFull()){
throw new RuntimeException("the queue is full, cannot add");
}
rear++;
queue[rear] = num;
}
// get items from the queue
public int getQueue(){
if(isEmpty()){
throw new RuntimeException();
}
front++;
return queue[front];
}
// show all the items in the queue
public void showQueue(){
if(isEmpty()){
System.out.println("queue is empty");
}
for (int i = 0; i < queue.length; i++) {
System.out.println("the items are"+ queue[i]);
}
}
public int headQueue(){
if(isEmpty()){
throw new RuntimeException();
}
return queue[front];
}
}
public static void main(String[] args) {
** ArrayQueue arrq = new ArrayQueue(5);**
char key = ' '; //input from the user
Scanner scanner = new Scanner(System.in);
boolean loop = true;
while(loop){
System.out.println("s(show): show queue");
System.out.println("e(exit): exit queue");
System.out.println("a(add): add items");
System.out.println("g(get): pop element");
System.out.println("h(show): get first element");
key = scanner.next().charAt(0);
switch (key) {
case 's':
arrq.showQueue();
break;
case 'a':
System.out.println("enter a number");
int value = scanner.nextInt();
arrq.addQueue(value);
break;
case 'g':
try {
int res = arrq.getQueue();
System.out.println("the items got poped is"+ res);
} catch (Exception e) {
//TODO: handle exception
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int res = arrq.headQueue();
System.out.println("the head item is"+ res);
} catch (Exception e) {
//TODO: handle exception
System.out.println(e.getMessage());
}
break;
case 'e':
scanner.close();
loop =false;
break;
default:
break;
}
}
System.out.println("End");
}
}
运行结果及报错内容
non-static variable this cannot be referenced from a static context
No enclosing instance of type ArrayQueueDemo is accessible. Must qualify the allocation with an enclosing instance of type ArrayQueueDemo (e.g. x.new A() where x is an instance of ArrayQueueDemo).