package com.an;
import java.util.Arrays;
import java.util.Scanner;
public class ArrayQueueDemo {
public static void main(String[] args) {
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':
queue.show();
break;
case 'a':
System.out.println("输入一个数");
int value = scanner.nextInt();
queue.add(value);
break;
case 'g':
try {
int res = queue.get();
System.out.printf("取出来的数来是%d\n",res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e':
scanner.close();
loop=false;
break;
default:
break;
}
}
System.out.println("程序退出");
}
}
class ArrayQueue {
private int maxSize;
private int head;
private int rear;
private int[] arr;
public ArrayQueue(int arrMaxSize) {
maxSize = arrMaxSize;
arr = new int[maxSize];
head = -1;
rear = -1;
}
// 判断队列是否满
public boolean isFull() {
return rear == maxSize - 1;
}
// 判断队列是否为空
public boolean isEmpty() {
return rear == head;
}
public void add(int n) {
if (isFull()) {
System.out.println("该队列已经满了");
} else {
rear++;
arr[rear] = n;
}
}
public void remove() {
if (isEmpty()) {
System.out.println("该队列已经空了了");
} else {
head++;
arr[head]=0;
System.out.println("第一个为:"+head);
}
}
public int get() {
if (isEmpty()) {
throw new RuntimeException("该队列为空,无法获取");
} else {
head++;
return arr[head];
}
}
public void show() {
if (isEmpty()) {
System.out.println("该队列没有数据");
} else {
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
public void showHead() {
if (isEmpty()) {
System.out.println("没有");
} else {
System.out.println("对头为:" + arr[head]);
}
}
@Override
public String toString() {
return "ArrayQueue [maxSize=" + maxSize + ", head=" + head + ", rear=" + rear + ", arr=" + Arrays.toString(arr)
+ "]";
}
}