import java.util.Scanner;
/**
* @author Rainful
* @create 2021/05/28
*/
class Main2{
public static void main(String[] args){
// 创建输入实例
Scanner sc = new Scanner(System.in);
System.out.println("请输入队列的大小");
int arrMaxLength;
try {
arrMaxLength = sc.nextInt();
} catch (Exception e) {
System.out.println("输入有误, 默认长度为3");
arrMaxLength = 3;
}
ArrQueueDemo2 queue = new ArrQueueDemo2(arrMaxLength);
boolean flag = true;
while (flag){
System.out.println("a 增加一个数据");
System.out.println("g 弹出一个数据");
System.out.println("h 打印头部数据");
System.out.println("p 打印全部数据");
System.out.println("e 退出程序");
char c = sc.next().charAt(0);
switch (c) {
case ‘a‘ -> {
if (queue.isFull()){
System.out.println("队列已满");
continue;
}
System.out.println("请输入数据");
queue.addQueue(sc.nextInt());
}
case ‘g‘ -> {
try{
queue.getQueue();
} catch (Exception e){
System.out.println(e.getMessage());
}
}
case ‘h‘ -> {
try{
queue.printHeadQueue();
} catch (Exception e){
System.out.println(e.getMessage());
}
}
case ‘p‘ -> {
try{
queue.printQueue();
} catch (Exception e){
System.out.println(e.getMessage());
}
}
case ‘e‘ -> {
System.out.println("程序关闭");
sc.close();
flag = false;
}
}
}
}
}
class ArrQueueDemo2{
private int arrMaxlength;
private int tailCount = -1;
private int[] queue;
// 接收输入 创建队列
public ArrQueueDemo2(int arrMaxLength) {
this.arrMaxlength = arrMaxLength;
queue = new int[this.arrMaxlength];
}
// 判断队列是否为空
public boolean isEmpty(){
return this.tailCount == -1;
}
// 判断队列是否已满
public boolean isFull(){
return this.tailCount == this.arrMaxlength - 1;
}
// add 增加一个数据
public void addQueue(int num){
this.tailCount++;
queue[this.tailCount] = num;
}
// get 弹出头部数据
public void getQueue(){
if (isEmpty()){
throw new RuntimeException("队列为空");
}
System.out.println(queue[0]);
this.tailCount--;
for(int i = 0; i < this.arrMaxlength - 1; i++){
queue[i] = queue[i + 1];
}
queue[queue.length -1] = 0;
}
// head 打印头部数据
public void printHeadQueue(){
if (isEmpty()){
throw new RuntimeException("队列为空");
}
System.out.println("头部数据为: " + queue[0]);
}
// print 打印队列全部数据
public void printQueue(){
if (isEmpty()){
throw new RuntimeException("队列为空");
}
for (int n : queue){
System.out.printf("%d\t", n);
}
System.out.println();
}
}
原文:https://www.cnblogs.com/rainful/p/14824125.html