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;
case 'h':
queue.showHead();
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 = 0;
rear = 0;
}
// 判断队列是否满
public boolean isFull() {
return (rear+1)%maxSize==head;
}
// 判断队列是否为空
public boolean isEmpty() {
return rear == head;
}
public void add(int n) {
if (isFull()) {
System.out.println("该队列已经满了");
} else {
arr[rear] = n;//加入数据
//向后移,考虑取模
rear=(rear+1)%maxSize;
}
}
public int get() {
if (isEmpty()) {
throw new RuntimeException("该队列为空,无法获取");
} else {
//先取出来第一个
System.out.println("拿:"+head);
int value=arr[head];
//head向后移
head=(head+1)%maxSize;
System.out.println("chu:"+head);
return value;
}
}
public void show() {
if (isEmpty()) {
System.out.println("该队列没有数据");
} else {
//从有数据的第一个开始遍历(head)
for (int i = head; i < head+size(); i++) {
System.out.printf("arr[%d]=%d\n",i%maxSize,arr[i%maxSize]);
}
}
}
public int size(){
return (rear+maxSize-head)%maxSize;
}
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)
+ "]";
}
}