import scala.io.StdIn
object ArrayQueue {
def main(args: Array[String]): Unit = {
var key = ""
val arrayQue = new ArrayQue(4)
while (true) {
println("show:表示显示队列")
println("exit:表示退出队列")
println("add:表示添加元素")
println("get:表示取数据")
key = StdIn.readLine()
key match {
case "show" => arrayQue.showQueue()
case "exit" => System.exit(0)
case "add" => {
println("请输入一个要添加的数字:")
val value = StdIn.readInt()
arrayQue.addQueue(value)
}
case "get" => {
val res = arrayQue.getQueue()
if (res.isInstanceOf[Exception]) {
println(res.asInstanceOf[Exception].getMessage)
}
println(res)
}
}
}
}
class ArrayQue(arrMaxSize: Int) {
val maxSize = arrMaxSize
val arr = new Array[Int](maxSize)
var front = -1
var rear = -1
//判断队列是否满
def isFull(): Boolean = {
rear == maxSize - 1
}
//判断队列是否空
def isNull(): Boolean = {
front == rear
}
//添加元素
def addQueue(n: Int) = {
if (isFull()) {
println("队列已满")
}
rear += 1
arr(rear) = n
}
//获取数据
def getQueue(): Any = {
if (isNull()) {
return new Exception("队列为空")
front = -1
}
front += 1
return arr(front)
}
//显示队列的所有数据
def showQueue(): Unit = {
if (isNull()) {
println("queue is empty")
return
}
for (i <- front + 1 to rear) {
printf("arr[%d]=%d\n", i, arr(i))
}
}
}
}