Java 为什么我的队列类像stack一样工作?
我需要java编程方面的帮助。谁能告诉我哪里做错了 我的Queue类像堆栈一样工作,而不是队列。如果我将1、2和3(按该顺序)排队,然后退出队列,它将删除3,而不是1 提前谢谢你 这是一个循环数组,下面是我的代码:Java 为什么我的队列类像stack一样工作?,java,arrays,stack,queue,Java,Arrays,Stack,Queue,我需要java编程方面的帮助。谁能告诉我哪里做错了 我的Queue类像堆栈一样工作,而不是队列。如果我将1、2和3(按该顺序)排队,然后退出队列,它将删除3,而不是1 提前谢谢你 这是一个循环数组,下面是我的代码: import java.util.NoSuchElementException; 公共类队列实现了QueueADT { 专用int前端=0; 私有int back=0; 私人机构【】a; 私有整数大小=10; 公共队列(){ a=新整数[10]; } 公共队列(整数大小){ a=新的
import java.util.NoSuchElementException;
公共类队列实现了QueueADT
{
专用int前端=0;
私有int back=0;
私人机构【】a;
私有整数大小=10;
公共队列(){
a=新整数[10];
}
公共队列(整数大小){
a=新的整数[大小];
这个。大小=大小;
}
//排队-在队列后面添加一个元素
公共void排队(int元素){
如果((后+1)-前)=-1 | |((后+1)-前)=(a.长度-1))
调整数组大小();
if(back==a.length-1)
后退=0;
一个[back++]=元素;
}
//出列-从队列中移除并返回元素
//排在队伍前面
公共整数出列(){
if(isEmpty())
抛出新的NoSuchElementException(“出列:队列为空”);
if(前<后){
前端++;
返回一个[front-1];
}
else if(前>后){
前面--;
返回一个[front++];
}
返回1;
}
//peek-返回但不从中删除元素
//队伍的前面
公共int peek(){
if(isEmpty())
抛出新的NoSuchElementException(“Peek:Queue为空”);
返回[正面];
}
//isEmpty-确定队列是否为空
公共布尔值为空(){
返回大小()==0;
}
私有void resizeArray()
{
//将数组的大小增加一倍
int[]newA=新int[a.长度*2];
int x=0;
而(x后){
返回大小-(前-(后+1));}
返回后-前+1;}
//返回队列的字符串表示形式
公共字符串toString(){
if(isEmpty()){
抛出新的NoSuchElementException(“队列为空”);
}
{
字符串s=“[”;
//打印队列
对于(int i=0;i
队列的行为不像堆栈。它的行为就像一个马车队列
public static void main(String[] args) {
Queue q = new Queue();
q.enqueue(7);
q.enqueue(8);
q.enqueue(9);
System.out.println(q.dequeue()); // 7 (ok)
System.out.println(q.dequeue()); // 8 (ok)
System.out.println(q.dequeue()); // 9 (ok)
System.out.println(q.dequeue()); // 1 (bug)
System.out.println(q.dequeue()); // 1 (bug)
System.out.println(q.dequeue()); // 1 (bug)
}
您的代码在哪里,使您在第一次调用
dequeue
时断定它正在删除3?您的队列有严重的问题
下面是一个单元测试的开始,它测试您的队列并显示一些bug
import org.junit.Test;
import java.util.NoSuchElementException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class QueueTest {
final Queue queue = new Queue();
@Test
public void givenNewQueue_thenSizeIsZero() {
assertEquals(0, queue.size());
}
@Test
public void givenNewQueue_thenIsEmpty() {
assertTrue(queue.isEmpty());
}
@Test(expected = NoSuchElementException.class)
public void givenNewQueue_whenDequeing_thenThrowsException() {
queue.dequeue();
}
@Test
public void givenNewQueue_whenQueueingElement_thenIsNotEmpty() {
queue.enqueue(0xA113);
assertFalse(queue.isEmpty());
}
@Test
public void givenNewQueue_whenQueueingElement_thenSizeIsOne() {
queue.enqueue(0xA113);
assertEquals(1, queue.size());
}
@Test
public void givenNewQueue_whenQueueingElement_thenReturnsElement() {
queue.enqueue(0xA113);
assertEquals(0xA113, queue.dequeue());
}
}
旁注:在
equals()
中,codeboolean标志=false;对于…,如果(!flag)返回false如果(!(otherQ instanceof QueueADT))返回false,则可以用替换code>代码>.Sidenote 2:编写测试,使用TDD;)如果这应该是您提到的循环队列,为什么它会自动调整大小?