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

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

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

  1. package cs210;
  2. public class Queue
  3. {
  4. private int maxSize;
  5. private String[] queArray;
  6. private int front;
  7. private int rear;
  8. private int nItems;
  9. //constructor
  10. public Queue(int s)
  11. {
  12. maxSize = s;
  13. queArray = new String[maxSize];
  14. front = 0;
  15. rear = -1;
  16. nItems = 0;
  17. }
  18. //insert method to add to the rear of the queue
  19. public boolean insert(String j)
  20. {
  21. if(isFull())
  22. return false; //Can't add if full
  23. if(rear == maxSize-1)
  24. rear = -1; //wrap around
  25. rear++; // Increase rear
  26. queArray[rear] = j; //Insert value
  27. nItems++;//item number increased
  28. return true; // Insert successful
  29. }
  30. //remove method takes item from the front of the queue
  31. public String remove()
  32. {
  33. if(isEmpty())
  34. return null; //Don't remove if empty
  35. String temp = queArray[front]; //get value and increase front
  36. front++;
  37. if(front == maxSize)
  38. front = 0; //wrap around
  39. nItems--; //item number decreased
  40. return temp;
  41. }
  42. //peek method see the value at the front of the queue
  43. public String peekFront()
  44. {
  45. return queArray[front];
  46. }
  47. //check is queue empty(true)
  48. public boolean isEmpty()
  49. {
  50. return (nItems == 0);
  51. }
  52. //check is queue full(true)
  53. public boolean isFull()
  54. {
  55. return (nItems == maxSize);
  56. }
  57. //number of items in the queue
  58. public int size()
  59. {
  60. return nItems;
  61. }

}
这是我的主要课程

  1. package cs210;
  2. import java.util.Scanner;
  3. public class labquestion
  4. {
  5. public static void main(String arg[])
  6. {
  7. Scanner s = new Scanner(System.in);
  8. int queuesize = s.nextInt();
  9. Queue Q = new Queue(queuesize);
  10. s.nextLine();
  11. for (int i = 0; i < queuesize;i++)
  12. {
  13. String[] command = s.nextLine().split(" ");
  14. switch (command[0])
  15. {
  16. case"INSERT":
  17. Q.insert(command[1]);
  18. case"REMOVE":
  19. Q.remove();
  20. break;
  21. }
  22. }
  23. s.close();
  24. System.out.println(Q.size());
  25. System.out.println(Q.peekFront());
  26. }
2admgd59

2admgd591#

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

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

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

  1. case "REMOVE":

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

  1. case "INSERT":
  2. Q.insert(command[1]);
  3. break;
  4. case "REMOVE":
  5. Q.remove();
  6. break;
展开查看全部

相关问题