package ;
import ;
import ;
public class ArrayQueueDemo {
public static void main(String[] args) {
//测试
//创建一个队列
ArrayQueue queue = new ArrayQueue(3);
char key = ' '; //接收用户输入
Scanner scanner = new Scanner();//
boolean loop = true;
//输出一个菜单
while(loop) {
("s(show): 显示队列");
("e(exit): 退出程序");
("a(add): 添加数据到队列");
("g(get): 从队列取出数据");
("h(head): 查看队列头的数据");
key = ().charAt(0);//接收一个字符
switch (key) {
case 's':
();
break;
case 'a':
("输出一个数");
int value = ();
(value);
break;
case 'g': //取出数据
try {
int res = ();
("取出的数据是%d\n", res);
} catch (Exception e) {
// TODO: handle exception
(());
}
break;
case 'h': //查看队列头的数据
try {
int res = ();
("队列头的数据是%d\n", res);
} catch (Exception e) {
// TODO: handle exception
(());
}
break;
case 'e': //退出
();
loop = false;
break;
default:
break;
}
}
("程序退出~~");
}
}
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()) {
("队列满,不能加入数据");
return;
}
arr[++rear]=n;
}
//获取数据,出队列
public int getQueue() {
//判断是否空
if (isEmpty()) {
//通过抛出异常
throw new RuntimeException("队列空,不能取");
}
return arr[++front];
}
//显示队列数据
public void showQueue() {
//遍历
if (isEmpty()) {
("队列空,无数据");
}
for (int i = 0; i < ; i++) {
("arr[%d]=%d\n",i,arr[i]);
}
}
//显示队列头部数据,不是取出数据
public int headQueue() {
if (isEmpty()) {
throw new RuntimeException("队列空,无数据");
}
return arr[front+1];
}
}