import java.util.Scanner;
public class ArrayQueueDemo {
public static void main(String[] args) {
ArrayQueue queue = new ArrayQueue(3);
boolean loop = false;
char key = ' ';//接收用户输入
Scanner scanner = new Scanner(System.in);
System.out.println("s(show):显示队列");
System.out.println("e(exit):退出程序");
System.out.println("a(add):添加数据到队列");
System.out.println("g(get):从队列中取出数据");
System.out.println("h(head):查看队列头的数据");
while(loop){
key = scanner.next().charAt(0);//输入的数据
switch (key) {
case 's' :
queue.showQueue();
break;
case 'e':
scanner.close();
loop =false;
break;
case 'a':
System.out.println("输入一个数");
int num = scanner.nextInt();
queue.addQueue(num);
break;
case 'g':
try {
int result = queue.getQueue();
System.out.printf("取出的数据是%d",result);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int head = queue.headQueue();
System.out.printf("队列头的数据为%d",head);
} catch (Exception e) {
// TODO: handle exception
}
break;
default:
break;
}
}
}
}
//数组模拟队列类
class ArrayQueue{
private int maxSize;//数组的最大容量
private int front; //队列头
private int rear; //队列尾
private int arr[]; //用于存放数据,模拟队列
public ArrayQueue(int maxSize){
this.maxSize = maxSize;
arr = new int [maxSize];
front = -1; //指向队列投的前一个位置
rear = -1; //指向队列尾的位置,包括队列尾
}
//判断队列是否已满
public boolean isFull(){
return rear == maxSize -1;
}
//判断队列是否为空
public boolean isEmpty(){
return front == rear;
}
//向队列中添加数据
public void addQueue(int num){
if(isFull()){
System.out.println("队列已满");
return;
}
rear++;
arr[rear] =num;
}
//从队列中取数据
public int getQueue(){
if(isEmpty()){
throw new RuntimeException("队列为空");
}
front ++;
return arr [front];
}
//显示队列所有数据
public void showQueue(){
if(isEmpty()){
System.out.println("没有数据");
return;
}
for(int i=0;i<maxSize;i++){
System.out.printf("arr[%d]=%d\n",i,arr[i]);
}
}
//显示队列的头数据,不是取出数据
public int headQueue(){
if(isEmpty()){
throw new RuntimeException("队列为空");
}
return arr[front +1];
}
}