package com.atguigu.queue; import java.util.Scanner; public class ArrayQueueDemo { public static void main(String[] args) { ArrayQueue queue = new ArrayQueue(3); char order = ' '; boolean flag = true; Scanner s = new Scanner(System.in); while (flag){ System.out.println("s(show):显示队列"); System.out.println("g(get):取出队列的数据"); System.out.println("a(add):往队列里加数据"); System.out.println("h(headShow):显示队列头部数据"); System.out.println("e(exit):退出程序"); order = s.next().charAt(0);//接受第一个字母 switch (order){ case 's' : queue.showQueue(); break; case 'a': System.out.println("请加入一个数据:"); int val = s.nextInt(); queue.addQueue(val); break; case 'g': try { int res = queue.getData(); System.out.printf("返回的数据为%d\n",res); }catch (Exception e){ System.out.println(e.getMessage()); } break; case 'h': try { int res = queue.headQueue(); System.out.printf("取出的头部数据为%d\n",res); }catch (Exception e){ System.out.println(e.getMessage()); } break; case 'e': //关闭输入器 s.close(); flag = false; break; default: break; } } System.out.println("退出程序!"); } } class ArrayQueue{ private int maxSize; //数组最大容量 private int front; //指向数组最前面之前一个的数据 private int rear; //指向数组最后的数据(就是最后一个数据) private int[] arr; //有参构造 public ArrayQueue(int arrCount){ this.maxSize = arrCount; this.arr = new int[arrCount]; front = -1; rear = -1; } //判断是否满了 public boolean isFull(){ return rear == maxSize-1; } //判断是否为空 public boolean isEmpty(){ return front == rear; } //添加数据addQueue public void addQueue(int data){ //先判断是否满了 if (isFull()){ System.out.println("数组满了!"); return; } System.out.println(rear); //添加 rear++; System.out.println(rear); arr[rear] = data; } //取出数据 public int getData(){ //先进先出 //判断是否为空 if (isEmpty()) { //这里不能return一个-1,因为可能返回-1这个值 //抛异常 throw new RuntimeException("数组为空,发生异常!"); } front++; return arr[front];//先进先出,front指向队首 } //展示数组 public void showQueue(){ //先判断是否为空 if (isEmpty()) { System.out.println("数组为空!"); return; } for (int i = 0; i < arr.length; i++) { System.out.println("arr["+i+"]"+arr[i]); //格式化 //System.out.printf("arr[%d]=%d\n", i , arr[i]); } } //显示队列的头部,注意这里不是取数据 public int headQueue(){ if (isEmpty()) { throw new RuntimeException("数组为空!"); } return arr[front+1]; } }
ArrayQueueDemo
最新推荐文章于 2022-03-31 23:01:47 发布