//最后的效果是按a或者c键可以产生不同的音调,additional部分暂时无力写了,希望有更多人发一下解法,即使没写完,也可以互相参考。。。。
ArrayRingBuffer.java
// Make sure to make this class a part of the synthesizer package
//package <package name>;
package synthesizer;
public class ArrayRingBuffer extends AbstractBoundedQueue {
/* Index for the next dequeue or peek. */
private int first;
/* Index for the next enqueue. */
private int last;
/* Array for storing the buffer data. */
private double[] rb;
/** Create a new ArrayRingBuffer with the given capacity. */
public ArrayRingBuffer (int capacity){
// TODO: Create new array with capacity elements.
// first, last, and fillCount should all be set to 0.
// this.capacity should be set appropriately. Note that the local variable
// here shadows the field we inherit from AbstractBoundedQueue.
this.capacity = capacity;
this.rb = new double[capacity];
this.fillCount= 0;
this.first = 0;
this. last = 0;
}
/** Adds x to the end of the ring buffer. If there is no room, then
* throw new RuntimeException("Ring buffer overflow")
*/
public void enqueue(double x) {
// TODO: Enqueue the item. Don't forget to increase fillCount and update last.
// is there room?
if(this.capacity==this.fillCount)
throw new RuntimeException("try to enqueue a full queue");
else{
this.rb[this.last]=x;
this.last=(this.last+1)%this.capacity;
this.fillCount+=1;
}
}
/** Dequeue oldest item in the ring buffer. If the buffer is empty, then
* throw new RuntimeException("Ring buffer underflow");
*/
public double dequeue() {
// TODO: Dequeue the first item. Don't forget to decrease fillCount and update first.
if(this.fillCount==0)
throw new RuntimeException("try to dequeue in an empty queue");
else{
double result=this.rb[first];
this.first=(this.first+1)%this.capacity;
this.fillCount--;
return result;
}
}
/** Return oldest item, but don't remove it. */
public double peek() {
// TODO: Return the first item. None of your instance variables should change.
if(this.fillCount==0)
throw new RuntimeException("try to peek an empty queue");
else{
return this.rb[first];
}
}
public boolean isFull(){
if(this.fillCount==this.capacity)
return true;
else
return false;
}
public boolean isEmpty(){
if(this.fillCount==0)
return true;
else
return false;
}
public int fillCount(){
return this.fillCount;
}
}