我正在为一个类的项目工作,我们将把我们从书中倾斜的代码放在一起组成一个循环队列(在这个项目中称为环形缓冲区),经过几个小时的阅读/修复错误并将所有内容放在一起我结束了这个:
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.io.BufferedInputStream;
import java.io.PrintWriter;
import java.io.OutputStreamWriter;
public class RingBuffer<Item> implements Iterable<Item>
{
private int maxSize,size,first,last;
private Item[] buffer;
public RingBuffer(int maxSize)
{
this.maxSize=maxSize;
buffer=(Item[])new Object[maxSize];
}
public boolean isEmpty(){return size==0;}
public boolean isFull(){return size==maxSize;}
public void enqueue(Item item)
{
if(isFull())
throw new RuntimeException("The buffer is full");
buffer[last]=item;
last++;
if(last==maxSize)
last=0;
size++;
}
public Item dequeue()
{
if(isEmpty())
throw new RuntimeException("The buffer is empty");
Item item=buffer[first];
first++;
if(first==maxSize)
first=0;
size--;
return item;
}
public Iterator<Item> iterator()
{
return new RingBufferIterator();
}
public class RingBufferIterator implements Iterator<Item>
{
private int current;
private boolean iterated;
public RingBufferIterator()
{
current=first;
}
public boolean hasNext()
{
if(iterated)
return current!=last;
return true;
}
public Item next()
{
if(!hasNext())
throw new NoSuchElementException();
Item result=buffer[current];
current++;
if(current==maxSize)
current=0;
iterated=true;
return result;
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
public static void main(String[] args)
{
Scanner input=new Scanner(new BufferedInputStream(System.in));
PrintWriter output=new PrintWriter(new OutputStreamWriter(System.out),true);
RingBuffer<String> ring=new RingBuffer<String>(5);
while(input.hasNext())
{
String item=input.next();
if(!item.equals("-"))
ring.enqueue(item);
else if(!ring.isEmpty())
output.print(ring.dequeue()+" ");
}
output.println();
for(String st:ring)
output.print(st+" ");
output.println();
}
}
没有错误,但是我们获得了为分配运行的args,我在netbeans的运行设置中添加了。大约一个半小时前我按下了它,它仍在运行。我之前从未遇到过像cs学生那样的问题,并且想知道是什么原因造成的。在编码中是否需要更改任何内容,或者某些代码需要花费很长时间才能运行,我应该等待它吗?提前致谢