package com.dai.queue; import java.util.Scanner; public class ArrayQueueDemo { public static void main(String[] args) { //创建一个队列对象 ArrayQueue arrayQueue = 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(append):添加数据到队列"); System.out.println("g(get):从队列取出数据"); System.out.println("h(head):查看队列头数据"); key = scanner.next().charAt(0); switch (key) { case 's': arrayQueue.showQueue(); break; case 'a': System.out.println("输入数字:"); int value = scanner.nextInt(); arrayQueue.addQueue(value); break; case 'g': try { int res = arrayQueue.getQueue(); System.out.printf("取出的数据是%d ",res); }catch(Exception e) { System.out.println(e.getMessage()); } break; case 'h': try { int res = arrayQueue.headQueue(); System.out.printf("队列头的数据是%d ",res); }catch(Exception e) { System.out.println(e.getMessage()); } break; case 'e': scanner.close(); loop = false; break; default: break; } } System.out.println("程序退出"); } } //使用数组模拟队列,编写一个ArrayQueue类 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; //指向队列头部,的前一个位置 rear = -1;//指向队列尾 } //判断队列是否满 public boolean isFull() { return rear == maxSize-1; } public boolean isEmpty() { return rear==front; } //添加数据带队列 public void addQueue(int n) { //判断队列是否满 if(isFull()) { System.out.println("队列已满,无法添加数据"); return ; } rear ++; //rear后移 arr[rear] = n; } //获取队列数据,出队 public int getQueue() { if(isEmpty()) { throw new RuntimeException("对列空,不能取数据"); } front ++; return arr[front]; } //显示队列所有数据 public void showQueue() { if(isEmpty()) { System.out.println("队列空,无数据"); return; } int tmp = front; while(!isEmpty()) { System.out.printf("%d ",getQueue()); } front = tmp; } //显示队列的头数据 public int headQueue() { if(isEmpty()) { throw new RuntimeException("队列空,没有数据"); } return arr[front+1]; } }