2012-04-13 97 views
1

我有一個程序創建一個隊列,將對象排入隊列,然後如果隊列不爲空則將它們一個接一個地出隊。我遇到的問題是每次檢查時隊列都會變空。排隊每個對象後,在隊列上調用打印,並打印出隊列的內容。具有對象的隊列對於isEmpty()返回true J​​ava

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; 
    } 
} 
+1

可能計數沒有在隊列中正確更新? – trutheality 2012-04-13 18:50:18

+1

沒有看到LinkedQueue的源代碼(你自己的課程?),不可能知道發生了什麼。 – 2012-04-13 18:51:07

+1

'return count == 0'就足夠了,不需要'if(bool)return true else retrun false' ... – Xaerxess 2012-04-13 18:57:23

回答

9
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)你應該看到不同的結果

相關問題