我已经编写了一个队列代码,但我对如何编写一个关于如何填充此队列值的测试用例感到很遗憾。如果有人可以提供帮助,我将不胜感激。
public class Queue {
private Double[] elements;
private int back;
private static final int FRONT = 0;
public static final int DEFAULT_CAPACITY = 10;
/** Construct a queue with an ad hoc capacity */
/** Construct a queue with the default capacity */
/** put a new object at the end of the queue;
* follow the model of StackOfIntegers to expand the capacity
* if the queue is full
*/
int initCapacity;
public Queue()
{
initCapacity = DEFAULT_CAPACITY;
elements = new Double [initCapacity];
}
public Queue(int newValue){
initCapacity = newValue;
elements = new Double [initCapacity];
}
public void enqueue(Double value) {
if (back == initCapacity){
initCapacity = initCapacity * 2;
Double [] elements2 = new Double [initCapacity];
for (int i =0; i < elements.length; i++){
elements2[i] = elements[i];
}
elements = elements2;
}
elements[back]= value;
back+=1;
}
/** Return and remove the front element from the queue ;
* this method must call the private method shift()
*/
public Double dequeue() {
Double temp = elements[FRONT] ;
shift();
back = back - 1;
// we have to temporarily store the current front of the line
return temp;
}
/** Return the element at the front of the queue for inspection */
public Double peek() {
return elements[FRONT];
}
/** Test whether the queue is empty */
public boolean isEmpty() {
return back == FRONT;
}
/** Return the number of elements in the queue */
public int getSize() {
return back;
}
/** shift everything one position to the front and null out the
old back of the line */
private void shift() {
for ( int i = 1; i < back; i++ )
elements[i-1] = elements[i] ;
elements[--back] = null ;
}
/** A rough-and-ready way to see what is going on in our queue */
public void dump() {
System.out.print( "Elements: " ) ;
for ( int i = 0; i < elements.length; i++ )
System.out.print( elements[i] + " " ) ;
System.out.println() ;
System.out.println( "Back: " + back ) ;
}
}
到目前为止,我已经写了这个用于填充队列的值,但我怀疑我错了。
public class TestQueueOfDoubles {
public static void main(String[] args){
Queue Object = new Queue( 12);
Queue DefaultObject = new Queue();
Queue Object2 = new Queue( 14);
Queue Object3 = new Queue( 9);
System.out.println(Object.initCapacity);
System.out.println(DefaultObject.initCapacity);
System.out.println(Object2.initCapacity);
System.out.println(Object3.initCapacity);
}
}
答案 0 :(得分:0)
您正在创建多个队列,我猜测这不是您想要的结果。
//You created your Queue here
Queue object = new Queue( 12);
现在你要填充。您需要add()或offer方法 您已经实施了入队方法,因此请使用它。
//Reference Queue you already instanciated and use the enqueue method
object.enqueue(12);
object.enqueue(14);
object.enqueue(9);
现在您拥有一个包含所需值的队列。您可以打印并检查所有值是否都在队列中,如下所示:
for(Double d : object.elements)
System.out.println(d);