import java.util.Scanner;
public class Start {
public static void main(String[] args) {
boolean loop = true;
Queue queue = new Queue(4);
while (loop) {
System.out.println("a(append):入队");
System.out.println("r(remove):出队");
System.out.println("h(head):查看队列头部情况");
System.out.println("e(exit):退出程序");
Scanner scanner = new Scanner(System.in);
char key = scanner.next().charAt(0);
switch (key) {
case 'a':
System.out.println("输入想要入队的元素值");
int num = scanner.nextInt();
try {
queue.addQueue(num);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'r':
try {
int number = queue.removeQueue(); // 与 case: 'b' 中 num 不能名字相同,考虑局部变量的作用域问题
System.out.println("出队元素为:" + number);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h':
try {
queue.headQueue();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e' :
scanner.close();
loop = false;
break;
default:
System.out.println("请输入正确序号");
break;
}
}
}
}
class Queue {
/*
应该实现的方法:
1. 队列初始化--->构造方法、setArr(int arrSize)方法
2. 元素加队列--->public void addQueue(int num)
3. 元素出队列(输出该元素)--->public int removeQueue()
4. 判断队列是否为满 ---> boolean isFull()
5. 判断队列是否为空 ---> boolean ifEmpty()
*/
int front = -1;
int rear = -1;
private int[] arr;
private int arrSize;
public Queue(int arrSize) {
this.arrSize = arrSize;
arr = new int[arrSize];
}
public Queue() {
}
public void setArr(int arrSize) {
this.arrSize = arrSize;
arr = new int[arrSize];
}
// 队列是否为满
public boolean isFull() {
return rear == arrSize - 1;
}
// 队列是否为空
public boolean isEmpty() {
return rear == front;
}
// 元素加队列
// 注意: 1. 判断队列是否为满 2. 未满则加入新元素
public void addQueue(int num) {
if (this.isFull()) {
throw new RuntimeException("队列已满,无法继续进队列");
}
rear++;
arr[rear] = num;
}
// 元素出队列
// 注意: 1. 出队列前判断队列是否为空 2. 未空则输出移除元素
public int removeQueue() {
if (this.isEmpty()) {
throw new RuntimeException("队列为空,无法继续出队列");
}
front++;
return arr[front];
}
public void headQueue() {
if(this.isEmpty()) {
throw new RuntimeException("队列为空");
}
System.out.println("arr的头部数据为:" + arr[front + 1]);
}
}