public class Main {public static void main(String[] args) {System.out.println("pop 出队");System.out.println("push 入队");System.out.println("show 展示队列数据");System.out.println("exit 结束程序");CycleQueue queue = new CycleQueue(5);Scanner outer = new Scanner(System.in);Scanner inner = new Scanner(System.in);System.out.println("------------------ read? go! ------------------");while (true) {String command = outer.nextLine();if ("pop".equals(command)) {try {int value = queue.pop();System.out.println(value);} catch (Exception e) {System.out.println(e.getMessage());}} else if ("push".equals(command)) {int value = inner.nextInt();queue.push(value);} else if ("show".equals(command)) {queue.show();} else if ("exit".equals(command)) {break;} else {System.out.println("不支持的操作");}}System.out.println("------------------over------------------");}static class CycleQueue {// 头指针private int head;// 尾指针private int tail;private int size;private int[] arr;public CycleQueue(int i) {size = i;arr = new int[size];}public boolean isFull() {return (tail + 1) % size == head;}public boolean isEmpty() {return head == tail;}/*** 出队*/public int pop() {if (isEmpty()) {throw new RuntimeException("队列为空~");}int res = arr[head];head = (head + 1) % size;return res;}/*** 入队*/public void push(int i) {if (isFull()) {System.out.println("队列已满~");return;}arr[tail] = i;tail = (tail + 1) % size;}public void show() {if (isEmpty()) {System.out.println("队列为空,无数据~");return;}// System.out.println("队列中的数据为:");// 计算队列中的元素数量int count = (tail - head + size) % size;// 通过循环展示所有数据for (int i = 0; i < count; i++) {int index = (head + i) % size;System.out.printf("arr[%d] = %d\n", index, arr[index]);}}}
}