命名基本规范,因为是日记不想浪费太多时间在解释说明上。
补充一个小知识点:使用RuntimeException而不是Exception的原因(简单理解就是想少写点代码),在最下方。
import java.util.Scanner;
public class Queue {
public static void main(String[] args) {
ArrQueue queue=new ArrQueue(3);
Scanner scan=new Scanner(System.in);
boolean loop=true;
while(loop){
System.out.print("请输入命令:");
char key=scan.next().charAt(0);
switch (key){
case 'a':
try {
System.out.print("输入要添加的数:");
int n=scan.nextInt();
queue.addQueue(n);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'g':
try {
int elem=queue.getQueue();
System.out.println("已取出元素:"+elem);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 's':
try {
queue.showQueue();
} 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':
scan.close();
loop=false;
System.out.println("程序退出!");
break;
default:
break;
}
}
}
}
class ArrQueue{
private int maxsize;
private int front;
private int rear;
private int[] arr;
public ArrQueue(int maxsize){
this.maxsize=maxsize;
arr=new int[maxsize];
front=-1;
rear=-1;
}
public boolean isFull(){
return rear==maxsize-1;
}
public boolean isEmpty(){
return front==rear;
}
public void addQueue(int n){
if(isFull()){
throw new RuntimeException("添加失败,队已满~");
}
arr[++rear]=n;
}
public int getQueue(){
if(isEmpty()){
throw new RuntimeException("取出失败,队已空~");
}
return arr[++front];
}
public void showQueue(){
if(isEmpty()){
throw new RuntimeException("无法显示,队已空~");
}
for (int i = front+1; i <=rear ; i++) {
System.out.println(arr[i]);
}
}
public void headQueue(){
if(isEmpty()){
throw new RuntimeException("无法显示,队已空~");
}
System.out.println(arr[front+1]);
}
}