java - 具有对象的队列为 isEmpty() Java 返回 true

标签 java queue is-empty

我有一个创建队列的程序,将对象排入队列,然后如果队列不为空,则将它们一个一个地出队。我遇到的问题是每次检查时队列都是空的。将每个对象排入队列后,在队列上调用打印,它会很好地打印队列的内容。

import java.util.*;
import java.io.*;
public class Processor2
{
private LinkedQueue queue = new LinkedQueue();
private int time = 0;
private int count = 100;
private int amount = 0;
private PrintWriter out;
private Person temp;
private boolean var;
private Random randomNum = new Random();;
private String turn;
private int popCount=0;
private int loopCount =0;

public void start()
{
    amount = randomNum.nextInt(5);
    amount += 5;
    pop(amount, time);
    sim();
}

public void pop(int num, int time)
{

        for(int i=1; i<=num; i++)
        {
            Person pe = new Person(i, time, 0);
            queue.enqueue(pe);
            System.out.println(queue);
        }   
        popCount += num;
}

public void sim()
{
    try
    {
        out = new PrintWriter(new FileWriter("output.txt")); 

        while(loopCount<=100)
        {
            var = queue.isEmpty();
            if(var=true)
            {
                System.out.println("queue is empty");
            }

            if(var=false)
            {
                Object temp = queue.dequeue();
                double rand = Math.random();

                if(rand < 0.5)
                {
                    System.out.println("inside if else statement");
                    // does stuff with object //
                    loopCount++;
                }
                else
                {
                    System.out.println("inside if else statement");
                    // does stuff with object //
                    loopCount++;
                }
            }
        }
        out.close();
    }
    catch (IOException ioe)
    {
        System.out.println("Error Writing to File: " + ioe);
    }
}
}

队列的 isEmpty() 方法似乎没有任何问题,但这里是:

public boolean isEmpty() 
{
    if(count == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

最佳答案

var = queue.isEmpty();
if(var=true) // this line *sets* var to true
{
    System.out.println("queue is empty");
}

如果您将 if (var=true) 更改为 if(var==true) 或只是 if(var) 您应该会看到不同的结果

关于java - 具有对象的队列为 isEmpty() Java 返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10146586/

相关文章:

java - 如何让一个jsp页面下载2个文件

java - Java SQLexecuteQuery 抛出有效 sql 语句错误

C# 容器 - 矢量,。列表、队列、堆栈等

VBA检查变量是否为空

java - 我可以相信 Files 中的方法会在预期时抛出 NoSuchFileException 吗?

python 3 : Using a multiprocessing queue for logging

java - 在Java中使用栈作为队列

php - CodeIgniter 3 - 具有 PHP 空函数的 session 项 getter

Javascript:避免多个弹出框/检查div是否为空

java - 通过继承隐藏字段