为什么我的队列大小总是为零?当调用insert时,它应该增加

ulydmbyx  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(351)

嗨,我必须将命令列表作为字符串,例如“insert one”或“remove”,并将它们应用到队列中,在命令执行完毕后,我必须编写自己的队列类队列大小始终为零,我需要稍后使用队列大小
这是我的排队课

package cs210;

public class Queue
{
    private int maxSize;
    private String[] queArray;
    private int front;
    private int rear;
    private int nItems;

//constructor
public Queue(int s)
{
    maxSize = s;
    queArray = new String[maxSize];
    front = 0;
    rear = -1;
    nItems = 0;
}

//insert method to add to the rear of the queue 
public boolean insert(String j)
{
    if(isFull())
        return false; //Can't add if full
    if(rear == maxSize-1)
        rear = -1; //wrap around
    rear++; // Increase rear
    queArray[rear] = j; //Insert value
    nItems++;//item number increased 
    return true; // Insert successful
}

//remove method takes item from the front of the queue
public String remove()
{
    if(isEmpty()) 
        return null; //Don't remove if empty
    String temp = queArray[front]; //get value and increase front
    front++;
    if(front == maxSize)
        front = 0; //wrap around
    nItems--; //item number decreased 
    return temp;
}

//peek method see the value at the front of the queue
public String peekFront()
{
    return queArray[front];
}

//check is queue empty(true)
public boolean isEmpty()
{
    return (nItems == 0);
}

//check is queue full(true)
public boolean isFull()
{
    return (nItems == maxSize);
}

//number of items in the queue 
public int size()
{
    return nItems;
}

}
这是我的主要课程

package cs210;

import java.util.Scanner;

public class labquestion 
{
public static void main(String arg[])
{ 

    Scanner s = new Scanner(System.in);
    int queuesize = s.nextInt();
    Queue Q = new Queue(queuesize);
    s.nextLine();

    for (int i = 0; i < queuesize;i++)
    {
        String[] command = s.nextLine().split(" ");
        switch (command[0]) 
            {
                case"INSERT":
                    Q.insert(command[1]);

                case"REMOVE":
                    Q.remove();
                    break;
            }

    }
    s.close();

    System.out.println(Q.size());
    System.out.println(Q.peekFront());

}
2admgd59

2admgd591#

插入的case后面没有break语句:

case "INSERT":
    Q.insert(command[1]);

case "REMOVE":
    Q.remove();
    break;

在没有中断语句的情况下,通过设计“fall-through”切换案例。这意味着他们将继续执行代码行,直到达到中断;语句或switch语句的结尾。
因此,在您的情况下,当您插入一个元素时,它也将始终执行

case "REMOVE":

因此,每次在队列中插入内容时,也会立即将其从队列中移除,这意味着大小始终保持为0。
要修复它,只需在insert case之后添加一个break:

case "INSERT":
    Q.insert(command[1]);
    break;            
case "REMOVE":
    Q.remove();
    break;

相关问题