Java:不可转换类型错误(使用数组队列)



我正在开发一个模拟餐厅座位系统的程序。我在排队(将对象放入队列)一方(对象)而不使变量在 Party 类中静态时遇到问题,因为如果我这样做,那么当我取消排队时,它会过度写入队列中的所有对象相同。

这是我的主程序代码:

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();
}
}

下面是 QueueArray 类中使用的 enqueue 方法:

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 类中的变量是静态的,这会导致覆盖问题?

不确定我是否正确回答了您的问题,但是行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包)——这会让你的生活更轻松。

最新更新