我正在开发一个模拟餐厅座位系统的程序。我在使方(对象)入队(将对象放入队列中)而在Party Class中使变量不静态时遇到了麻烦,因为如果这样做,那么当我出队时,它会将队列中的所有对象都写成相同。
这是我的主程序代码:
public static void main (String [] args)
throws IOException
{
//get name of simulation file from user and "open" that file
Scanner cin= new Scanner (System.in);
System.out.println("--- Welcome to the La Food Restaurant Simulator! ---");
System.out.println("Enter a data file name:");
String filename= cin.next();
Scanner fileread= new Scanner(new FileReader (filename));
Queue Q= new QueueArray(100);
boolean flag=true;
while (flag==true)
{
char action= fileread.next().charAt(0);
int seatedtime;
System.out.println(action); //TESTING PURPOSES ONLY
//if A read in party and put them in at the back of the queue (enqueue)
if(action=='A')
{
Party p= (Party)Q.enqueue(new Party(fileread));
System.out.println(p); //TESTING PURPOSES ONLY
//System.out.println(p.size); // TESTING PURPOSES ONLY
//System.out.println(p.name); // TESTING PURPOSES ONLY
//System.out.println("Please wait at the bar, party "+p.name+" of "+p.size+" people.");
}
//if T put the party at the front in the queue and remove them (dequeue)
if(action=='T')
{
seatedtime=fileread.nextInt();
System.out.println(seatedtime); //TESTING PURPOSES ONLY
Party p2=(Party) Q.dequeue();
System.out.println(p2.name);
//need a way to return the front object's (that was dequeued) info (size,name,arrival)
System.out.println("Table for "+p2.name "!");
}
// if Q stop the simulation
if(action=='Q')
{
flag=false;
}
}
System.out.println("---Simulation Terminated---");
System.out.println("The average waiting time was ");
System.out.println("The following parties were never seated:");
//print out info on the unseated party
}
}
这是我的派对类代码:
public class Party
{
int arrival;
int size;
String name;
//constructor of party object
public Party(Scanner file)
{
arrival=file.nextInt();
size= file.nextInt();
name= file.next();
name= name + file.nextLine();
}
}
这是QueueArrays类中使用的入队方法:
Object [] items;
int front;
int back;
int count;
public void enqueue(Object x)
{
if(isFull()) return; // do nothing
count++;
back++;
f(back>=items.length) back=0;
items[back]=x;
}
当我尝试编译主程序时,出现错误:
我排队参加聚会的那条路线上不可改变的类型。必填:发现的聚会:无效
如何解决这个问题而不仅仅是使用,Q.enqueue()
因为这需要我的Party Class中的变量为静态变量,从而导致覆盖问题?
不知道我是否正确回答了您的问题,但是Party p= (Party)Q.enqueue(new Party(fileread));
由于您的enqueue
方法返回了,因此该行将无法编译void
-您无法将其分配给变量。更改为
Party p = new Party();
Q.enqueue(p);
不过,我认为这里没有任何理由保持不变。
顺便说一句,为什么您要实施自己的Queue
而不使用Queue<Party> q = new LinkedList<Party>();
(从java.util
软件包中)类似的东西-这会使您的生活变得容易得多。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句