package queue;
import java.util.Scanner;
public class ArraryQueueDemo {
public static void main(String[] args) throws Exception {
ArrayQueue queue = new ArrayQueue(3);
char key = ' ';
Scanner scanner = new Scanner(System.in);
boolean loop = true;
while (loop) {
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):查看队列头的数据");
key = scanner.next().charAt(0);//接收一个字符
switch (key) {
case 's':
try {
queue.showQueue();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e':
loop = false;
break;
case 'a':
System.out.print("输出一个数:");
int value = scanner.nextInt();
queue.addQueue(value);
break;
case 'g':
try {
int queue1 = queue.getQueue();
System.out.println(queue1);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int i = queue.headQueue();
System.out.println(i);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
default:
break;
}
}
}
}
class ArrayQueue {
private int maxSize; //表示数组的最大容量
private int front; //队列头
private int rear; //队列尾
private int[] arr; // 该数据用于存储数据,模拟队列
// 创建队列的构造器
public ArrayQueue(int arrMaxSize) {
maxSize = arrMaxSize;
arr = new int[maxSize];
front = -1; // 指向队列头部,分析出front是指向队列头的第一个位置
rear = -1; // 指向队列尾,指向队列尾的数据(即就是队列最后一个数据)
}
// 判断队列是否满
public boolean isFull() {
return rear == maxSize - 1;
}
// 判断队列是否为空
public boolean isEmpty() {
return front == rear;
}
// 添加数据到队列
public void addQueue(int value) {
if (isFull()) {
System.out.println("队列已满,添加失败!");
return;
}
arr[++rear] = value;
}
//获取队列的数据,出队列
public int getQueue() throws Exception {
if (isEmpty()) {
throw new Exception("队列为空!");
}
int Result = arr[front + 1];
for (int i = front + 1; i < rear; i++) {
arr[i] = arr[i + 1];
}
rear--;
return Result;
}
//显示队列所有数据
public void showQueue() throws Exception {
if (isEmpty()) {
throw new Exception("队列为空!");
}
for (int i = front + 1; i <= rear; i++) {
System.out.println(arr[i]);
}
}
//显示队列的头数据
public int headQueue() throws Exception {
if (isEmpty()) {
throw new Exception("队列为空!");
}
return arr[front + 1];
}
}
06-05
1527
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)