數(shù)組模擬隊(duì)列
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ArrayQueue {
public static void main(String[] args) throws IOException {
ArrayQ arrayQ = new ArrayQ(5);
while (true){
System.out.println("選擇你要的服務(wù):");
System.out.println("輸入1:添加新元素");
System.out.println("輸入2:刪除指定個數(shù)元素");
System.out.println("輸入3:使用指定個數(shù)元素");
System.out.println("輸入0:展示全部隊(duì)列");
System.out.println("我選擇:");
switch (getIf()) {
case 1: {
System.out.println("需要添加的元素是:");
arrayQ.add(getIf());
break;
}
case 2: {
System.out.println("需要刪除的元素個數(shù)是:");
arrayQ.delete(getIf());
}
case 3: {
System.out.println("需要使用的元素個數(shù)是:");
arrayQ.use(getIf());
}
case 0: {
arrayQ.shows();
}
}
}}
private static int getIf() throws IOException {
InputStreamReader inp;
BufferedReader br;
inp = new InputStreamReader(System.in);
br = new BufferedReader(inp);
return Integer.parseInt(br.readLine());
}
}
class ArrayQ {
private int maxize;
private int front = -1;
private int rear = -1;
private int[] arr;
public ArrayQ(int maxize) {
this.maxize = maxize;
arr = new int[this.maxize];
}
public void shows() {
for (int i = 0; i <= rear; i++){
System.out.print(arr[i] + " " + i + ",");}
System.out.println();
}
public boolean isEmpty() {
return rear == front;
}
public void add(int s) {
if (isFull()) throw new RuntimeException("隊(duì)列已滿");
arr[++rear] = s;
}
public void delete(int i) {
while (i >= 0) {
arr[rear--] = 0;
i--;
}
}
public boolean isFull() {
return rear == maxize - 1;
}
public void use(int i) {
for (int n = 0; n < i; n++) {
System.out.println(arr[front + 1]);
for (int m = 0; m <= rear; m++) {
arr[m] = arr[m + 1];
}
rear--;
if (isEmpty()) {
throw new RuntimeException("隊(duì)列已空");
}
}
}
}