public static void main(String args[]) throws IOException {
ArrayQueue arrayQueue = new ArrayQueue(3);
char key=' ';//接收用户输入
Scanner scan= new Scanner(System.in);
boolean loop=true;
while (loop){
System.out.println("s:显示队列");
System.out.println("e:退出程序");
System.out.println("a:添加数据到队列");
System.out.println("g:队列里取数据");
System.out.println("h:显示头");
System.out.println("r:显示尾");
key = scan.next().charAt(0);
switch (key){
case 's':
try {
arrayQueue.showQueue();
System.out.println("已显示全部数据");
}catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'a':
try {
System.out.println("请输入一个数据");
int val=scan.nextInt();
arrayQueue.addQueue(val);
System.out.println("已成功添加数据");
}catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'g':
try {
int res=arrayQueue.getQueue();
System.out.printf("%d\n",res);
}catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h' :
try{
int res=arrayQueue.headQueue();
System.out.printf("取出的数据是:%d\n",res);
}catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'r':
try{
int res= arrayQueue.rearQueue();
System.out.printf("取出的数据是:%d\n",res);
}catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e':
scan.close();
loop=false;
break;
default:
break;
}
}
System.out.println("程序退出");
}
class ArrayQueue{
//属性
private int maxSize;//最大容器
private int front;//队列头
private int rear;//队列尾
private int[] arr;//用于存放数据,模拟队列
//创建队列的构造器
public ArrayQueue(int arrMaxSize) {
maxSize = arrMaxSize;
arr=new int[arrMaxSize];
front = rear =0;
}
//判断队列空
public boolean isEmpty() {
return front ==rear;
}
//判断队列满的
public boolean isFull() {
if(rear!=front)
return (rear-front)%maxSize==0;
return false;
}
//添加数据
public void addQueue(int n){
//判断队列是否满
if(isFull())throw new RuntimeException("队列满不能添加数据");
int val=rear;
rear++;
arr[val%maxSize]=n;
}
//取数据
public int getQueue(){
if(isEmpty())throw new RuntimeException("没有数据!");
int val =front;
front++;
return arr[val%maxSize];
}
//显示所有数据
public void showQueue(){
if(isEmpty()){
throw new RuntimeException("队列为空!");
}
for(int i=front;i<rear; i++){
System.out.printf("arr[%d]=%d\n",i%maxSize,arr[i%maxSize]);
}
}
//显示头数据
public int headQueue(){
if (isEmpty()) {
throw new RuntimeException("没有数据");
}
return arr[front%maxSize];
}
//显示尾数据
public int rearQueue(){
if (isEmpty()) {
throw new RuntimeException("没数据");
}
return arr[(rear-1)%maxSize];
}
}
来源:CSDN
作者:fylive
链接:https://blog.csdn.net/qq_39472229/article/details/103827398