我的队列类有问题。队列基于数组。当队列项到达数组的末尾时,应将它们添加到数组的开头。如果队列已满,则应删除并显示最旧的队列项。插入第8个元素时,显示删除的最旧项目时出现问题。
当用户选择显示前3个客户的名称时,代码应逐个从队列中删除(先进先出)并在删除时显示它们。
输入和输出示例:
队列输入是:
一个
b
C
d
Ë
F
G
ħ
队列输出是:
H
b
C
d
Ë
F
克
删除的项目是:h
预期输出应为:
H
b
C
d
Ë
F
G
删除的项目是:a
所以它将最后插入的项目移动到数组的前面但是如何显示"删除的项目是:a"
我的代码是:
public class MyQueue {
private final static int CAPACITY = 7;
static String qitems[] = new String[CAPACITY];
private static int front = 0, end = 0, count=0;
public void addqueue(String name) {
qitems[end] = name;
count++;
if(count==7) {
takequeue();
System.out.println("Queue is full");
}
end = (end + 1) % 7;
}
public void takequeue() {
System.out.println("Item removed:"+qitems[front]);
front = (front +1) % 7;
}
public void displayNames() {
System.out.println(" 3 names entered are: ");
for (int x = 0; x < 3; x++) {
System.out.println(qitems[x]);
}
}
}
答案 0 :(得分:1)
public class QWithArray {
String[] qItems;
int front;
int end;
int current;
QWithArray(int CAPACITY) {
qItems = new String[CAPACITY];
current = 0;
front = -1;
end = -1;
}
public void addqueue(String element) {
if (current == qItems.length) {
System.out.println("Item removed was: " + qItems[(front + 1) % qItems.length]);
}
front = (front + 1) % qItems.length;
qItems[front] = element;
current++;
if (end == -1) {
end = front;
}
}
public String takequeue() {
if (current == 0) {
System.out.println("Queue is empty; can't remove.");
return null;
}
String result = qItems[end];
qItems[end] = null;
end = (end + 1) % qItems.length;
current--;
if (current == 0) {
front = -1;
end = -1;
}
return result;
}
public static void main(String[] args) {
QWithArray q = new QWithArray(7);
q.addqueue("a");
q.addqueue("b");
q.addqueue("c");
q.addqueue("d");
q.addqueue("e");
q.addqueue("f");
q.addqueue("g");
System.out.println(Arrays.toString(q.qItems));
q.addqueue("h");
System.out.println(Arrays.toString(q.qItems));
}
}
输出将是:
[a, b, c, d, e, f, g]
Item removed was: a
[h, b, c, d, e, f, g]
答案 1 :(得分:0)
我通过添加以下main来运行您的代码。它打印&#34;项目已删除:a&#34;。粘贴在&#34; main&#34;所以我们可以看到你在做什么。
public static void main(String [] args) {
MyQueue q = new MyQueue();
q.addqueue("a");
q.addqueue("b");
q.addqueue("c");
q.addqueue("d");
q.addqueue("e");
q.addqueue("f");
q.addqueue("g");
q.addqueue("h");
}
答案 2 :(得分:0)
你的addQueue方法中的问题是你在检查它是否等于零之前增加计数。因此,在添加第7个项目后,条件count == 7
将评估为true,从而激活takeQueue方法。所以&#34;项目已删除:a&#34;将被打印出来。简单的解决方法是在检查它是否等于7后增加count
。
public void addqueue(String name)
{
if(count>=7)
{
takequeue();
System.out.println("Queue is full");
}
qitems[end] = name;
count++;
end = (end + 1) % 7;
}