I was wondering how I would add a trace to the stack of this code that converts infix to postix for expressions.
class Node {
public Object data;
public Node next;
public Node () {
data =' '; next = null; }
public Node (Object val) {
data = val; next = null; }
}
public class LinkStack {
private Node top;
public LinkStack() {
top = null; }
public boolean empty(){
return top == null; }
public boolean full(){
return false;
}
public void push(Object e){
Node tmp = new Node(e);
tmp.next = top;
top = tmp;
}
public Object pop(){
Object e = top.data;
top = top.next;
return e;
}
public Object peek(){
Object e = top.data;
return e;
}
public void matching(String x)
{
LinkStack S=new LinkStack();
for(int i=0;i<x.length();i++)
{
char c=x.charAt(i);
if(c=='(')
S.push(c);
else
{
if(c==')')
if(S.empty())
System.out.println("NOT MATCHING !!!");
else
S.pop();
}
}
if(!S.empty())
System.out.println("NOT MATCHING !!!");
else
System.out.println("MATCHING !!!");
}
public void Evaluation(String x)
{
LinkStack S=new LinkStack();
for(int i=0;i<x.length();i++)
{
char c=x.charAt(i);
String s="0"+c;
if(c=='+')
{
int z=Integer.parseInt((String)S.pop())+Integer.parseInt((String)S.pop());
S.push(Integer.toString(z));
}
else if(c=='*')
{
int z=Integer.parseInt((String)S.pop())*Integer.parseInt((String)S.pop());
S.push(Integer.toString(z));
}
else if(c=='/')
{ int u=Integer.parseInt((String)S.pop());
int z=Integer.parseInt((String)S.pop())/u;
S.push(Integer.toString(z));
}
else if(c=='-')
{ int u=Integer.parseInt((String)S.pop());
int z=Integer.parseInt((String)S.pop())-u;
S.push(Integer.toString(z));
}
else
S.push(s);
}
System.out.println("THE POSTFIX = "+x);
System.out.println("THE RESULT = "+S.pop());
}
public void postfix(String x)
{
String output="";
LinkStack S=new LinkStack();
for(int i=0;i<x.length();i++)
{
char c=x.charAt(i);
if(c==('+')||c==('*')||c==('-')||c==('/'))
{while(!S.empty() && priority(S.peek())>= priority(c))
output+=S.pop();
S.push(c);
System.out.println(output);
}
else if(c=='(')
{
S.push(c);
}
else if(c==')')
{
while(!S.peek().equals('('))
output+=S.pop();
S.pop();
System.out.println(output);
}
else
{
output+=c;
System.out.println(output);
}
}
while(!S.empty())
output+=S.pop();
System.out.println("THE INFIX = "+x);
System.out.println("THE POSTFIX = "+output);
}
public int priority(Object x)
{
if(x.equals('+')||x.equals('-'))
return 1;
else if(x.equals('*')||x.equals('/'))
return 2;
else
return 0;
}
public static void main(String args[])
{
LinkStack s=new LinkStack();
s.postfix("x*y–z+(a–c/d)");
System.out.println("------------------------------------------");
s.matching("x*y–z+(a–c/d)");
System.out.println("------------------------------------------");
}
}
I am pretty much wanting to follow the contents of the stack throughout the conversion
There's no rocket science solution to this.
Just add System.err.println(...) calls at the relevant places. Or if you were doing this in production code (heaven forbid!) you might use a Logger instead of System.err.
(For the record, the term "stack trace" normally means a trace of a program's call stack, not a trace of what happens to some application-specific stack data structure. You might want to choose your terminology a little more carefully next time.)
Related
I am trying to make a generic class called reverser that takes the contents of a text file and reverses the order of the contents. I am required to do this by using the generic stack class provided. I have to make sure that it works for two types, strings, and floats as they have been instantiated in main.
I am aware I can't push int values (as is returned by BufferedInputStream) onto the stack. My question is what may be a solution to this problem, should I instantiate two different versions of the generic stack class, one for strings and one for floats, or is there another solution?
public class project_5
{
public static void main(String[] args) throws Exception
{
Reverser<String> reversePoem = new Reverser<String>();
Reverser<Float> majiGame = new Reverser<Float>();
}
}
class Reverser<E>
{
private Stack<E> tempStack;
int k = 0;
int val = 0;
public Reverser()
{
tempStack = new Stack<E>();
}
void FileToStack(String fileIn) throws Exception
{
E item = null;
try
{
BufferedInputStream readFile = new BufferedInputStream(new FileInputStream(fileIn));
for(k = 0; (val = readFile.read()) != -1; k++)
{
tempStack.push(val);
}
readFile.close();
}
catch(FileNotFoundException e)
{
System.out.print("File: " + fileIn + " Not Found");
}
catch(IOException e)
{
System.out.print("Reached end of file.");
}
}
void StackToFile(String fileIn)
{
try
{
PrintWriter fileOut = new PrintWriter(fileIn);
fileOut.println();
fileOut.close();
}
catch(FileNotFoundException e)
{
}
}
}
//Class Stack ---------------------------------------
class Stack<E>
{
// pointer to first node in stack
private Node<E> top;
// constructor
public Stack()
{
top = null;
}
public boolean isEmpty()
{
return top == null;
}
public void push(E data)
{
if (data == null)
return;
// build a node and place it on the stack
Node<E> newNode = new Node<E>(data);
newNode.next = top;
top = newNode;
}
public E pop()
{
Node<E> temp;
temp = top;
if (isEmpty())
return null;
top = top.next;
return temp.getData();
}
// console display
public String toString()
{
Node<E> p;
String showAll = "";
// Display all the nodes in the stack
for( p = top; p != null; p = p.next )
showAll += p.toString() + "\n";
return showAll;
}
}
Edit: Removed pictures, added code in text format.
I have made a change to your logic where you are reading a file and then putting into the stack,
You have not put your Node class so I have added that accordingly
You need to typecast your value when reading from file
Note: in case of the file contains improper data you will get a casting error, that you need to handle
source.txt
1 2 3 4 5
target.txt
5
4
3
2
1
Code
import java.io.*;
import java.util.Arrays;
public class Test
{
public static void main(String[] args) throws Exception
{
Reverser<String> reversePoem = new Reverser<String>(String.class);
Reverser<Float> majiGame = new Reverser<Float>(Float.class);
majiGame.FileToStack("source.txt");
majiGame.StackToFile("target.txt");
}
}
class Reverser<E>
{
private Stack<E> tempStack;
private Class<E> tClass;
public Reverser(Class<E> tClass)
{
tempStack = new Stack<E>();
this.tClass = tClass;
}
public static <E> E convertInstanceOfObject(String value, Class<E> clazz) {
try {
// add custom casting, casting could be varies as par usage
if (clazz.getName().equals("java.lang.Integer")) {
return (E)Integer.valueOf(value);
} else if (clazz.getName().equals("java.lang.Float")) {
return (E)Float.valueOf(value);
} else if (clazz.getName().equals("java.lang.String")) {
return (E)value;
}
return clazz.cast(value);
} catch(ClassCastException e) {
return null;
}
}
void FileToStack(String fileIn) throws Exception
{
BufferedReader br;
try
{
br = new BufferedReader(new FileReader(fileIn));
String line = null;
while((line = br.readLine()) != null)
{
String[] valueArray= line.split(" ");
for (String v : valueArray) {
E item = convertInstanceOfObject(v, tClass);
tempStack.push(item);
}
}
br.close();
}
catch(FileNotFoundException e)
{
System.out.print("File: " + fileIn + " Not Found");
}
catch(IOException e)
{
System.out.print("Reached end of file.");
}
}
void StackToFile(String fileIn)
{
try
{
PrintWriter fileOut = new PrintWriter(new FileWriter(fileIn));
E d = null;
while (!tempStack.isEmpty()) {
d = tempStack.pop();
fileOut.println(d);
}
fileOut.close();
}
catch(IOException e)
{
}
}
}
class Node<E> {
Node<E> next;
private E data;
public Node(E data) {
this.data = data;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> next) {
this.next = next;
}
public E getData() {
return data;
}
public void setData(E data) {
this.data = data;
}
}
//Class Stack ---------------------------------------
class Stack<E>
{
// pointer to first node in stack
private Node<E> top;
// constructor
public Stack()
{
top = null;
}
public boolean isEmpty()
{
return top == null;
}
public void push(E data)
{
if (data == null)
return;
// build a node and place it on the stack
Node<E> newNode = new Node<E>(data);
newNode.next = top;
top = newNode;
}
public E pop()
{
Node<E> temp;
temp = top;
if (isEmpty())
return null;
top = top.next;
return temp.getData();
}
// console display
public String toString()
{
Node<E> p;
String showAll = "";
// Display all the nodes in the stack
for( p = top; p != null; p = p.next )
showAll += p.toString() + "\n";
return showAll;
}
}
Hi I need help fixing this OutOfMemoryError for my WordLadder program. Basically I after being halfway through the input wordladder file which contains the start and end words to create the world ladders it slows down significantly and the error occurs. I believe the error is due to the creation of several stacks without removal of already used ones.
The error occurs at Line: 74 in the WordStack file in the getNewStacks method which, as the name says, is supposed to get new stacks.
Below are all the required files:
Dictionary txt:
https://drive.google.com/file/d/1vl6N4-3IYK86lGxmf0hqP7nX2e0BYrim/view?usp=sharing
input txt:
https://drive.google.com/file/d/1ahHBL0ivqhC0zh24DCFnar03hxTt7Awc/view?usp=sharing
WordLadder main:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordLadder {
public static void main(String args[]) throws FileNotFoundException {
Dictionary dictionary = new Dictionary(new File("dictionary.txt"));
Scanner scan = new Scanner(new File("input.txt"));
while (scan.hasNextLine()) {
String start = scan.next();
String stop = scan.next();
System.out.println(findLadder(start, stop, dictionary));
}
}
static String findLadder(String start, String end, Dictionary dictionary) {
if (!dictionary.contains(start) || !dictionary.contains(end)) {
return "No word ladder between \"" + start + "\" and \"" + end + "\".";
}
if (start.equals(end)) return start + " " + end;
LinkedList stackQueue = new LinkedList();
stackQueue.enqueue(new WordStack(start, end));
boolean continueSearch;
boolean success = false;
WordStack ladder = new WordStack();
do {
int queueSize = stackQueue.size();
continueSearch = false;
for (int stackIndex = 0; stackIndex < queueSize; stackIndex++) {
LinkedList newStacks = ((WordStack) stackQueue.dequeue()).getNewStacks(dictionary);
if (newStacks.size > 0) {
while (newStacks.size() > 0) {
WordStack next = (WordStack) newStacks.dequeue();
if (next.success()) {
success = true;
ladder = next;
break;
}
stackQueue.enqueue(next);
}
continueSearch = true;
}
if (success) break;
}
if (success) break;
} while (continueSearch);
if (success) return ladder.toString();
else return "No word ladder between \"" + start + "\" and \"" + end + "\".";
}
}
WordStack (location of error line 74) :
public class WordStack {
LinkedList words;
String targetWord;
boolean success;
WordStack() {
words = new LinkedList();
targetWord = "";
success = false;
}
WordStack(LinkedList list, String target) {
words = list;
targetWord = target;
success = false;
}
WordStack(String startWord, String target) {
words = new LinkedList();
words.push(startWord);
targetWord = target;
success = false;
}
int size() {
return words.size();
}
void push(String word) {
words.push(word);
}
void add(String word) {
push(word);
}
String pop() {
if (size() < 1) return null;
return (String) words.pop();
}
String topWord() {
return (String) words.peek();
}
WordStack deepCopy() {
return new WordStack(words.hardCopy(), targetWord);
}
void markSuccess() {
success = true;
}
boolean success() {
return success;
}
boolean contains(String word) {
WordStack compare = deepCopy();
while (compare.size() > 0) {
if (word.equals(compare.pop())) return true;
}
return false;
}
LinkedList getNewStacks(Dictionary dictionary) {
LinkedList stacks = new LinkedList();
for (int letterPos = 0; letterPos < topWord().length(); letterPos++) {
for (char letter = 'a'; letter <= 'z'; letter++) {
String newWord = topWord().substring(0, letterPos) + letter + topWord().substring(letterPos + 1, topWord().length());
if (dictionary.contains(newWord) && !contains(newWord)) {
WordStack newStack = deepCopy();
newStack.push(newWord);
if (newWord.equals(targetWord)) newStack.markSuccess();
stacks.enqueue(newStack);
}
}
}
return stacks;
}
public String toString() {
String returnString = "";
for (int index = size() - 1; index >= 0; index--) {
returnString += (String) words.getPeek(index) + " ";
}
return returnString;
}
}
Node class:
public class Node {
public Object data;
Node next;
Node() {
data = null;
next = null;
}
Node(Object data) {
this.data = data;
next = null;
}
Object get() {
return data;
}
void set(Object data) {
this.data = data;
}
Node getNextPtr() {
return next;
}
void setNextPtr(Node next) {
this.next = next;
}
public String toString() {
return "" + data;
}
}
LinkedList:
public class LinkedList {
Node head;
Node tail;
int size;
LinkedList() {
head = null;
tail = null;
size = 0;
}
LinkedList hardCopy() {
LinkedList copy = new LinkedList();
if(size() < 1) return copy;
Node current = head;
while(current.getNextPtr() != null) {
copy.addEnd(current.get());
current = current.getNextPtr();
}
copy.addEnd(current.get());
return copy;
}
void iterateHead() {
head = head.getNextPtr();
size--;
}
void addEnd(Object newObj) {
enqueue(newObj);
}
void add(Object newObj) {
Node newNode = new Node(newObj);
if(size == 0) {
head = newNode;
}
else {
newNode.setNextPtr(head);
head = newNode;
}
size++;
}
Object peek() {
return head.get();
}
void push(Object newObj) {
add(newObj);
}
void enqueue(Object newObj) {
Node newNode = new Node(newObj);
if(size < 1) {
head = newNode;
tail = newNode;
} else {
tail.setNextPtr(newNode);
tail = newNode;
}
size++;
}
Object pop() {
Node pop = head;
if(size > 1) {
head = head.getNextPtr();
size--;
return pop.get();
}
else if(size == 1) {
size--;
head = null;
return pop.get();
}
else return null;
}
Object dequeue() {
if(size < 1) return null;
Node dequeueNode = head;
if(size > 1) {
iterateHead();
}
else {
head = null;
tail = null;
size--;
}
return dequeueNode.get();
}
int size() {
return size;
}
Object getPeek(int index) {
if(index >= size) return null;
Node current = head;
for(int i = 0; i < index; i++) {
current = current.getNextPtr();
}
Object data = current.get();
return data;
}
}
I do apologize for the amount of required code for the program to run.
When I run my code for a method calculating the height of a binary search tree, it results in a Stack Overflow error, but only for trees with more than one node (BSTElements in my program). I have read that this is due to a faulty recursive call, but cannot identify the problem in my code.
public int getHeight() {
return getHeight(this.getRoot());
}
private int getHeight(BSTElement<String,MorseCharacter> element) {
int height=0;
if (element == null) {
return -1;
}
int leftHeight = getHeight(element.getLeft());
int rightHeight = getHeight(element.getRight());
if (leftHeight > rightHeight) {
height = leftHeight;
} else {
height = rightHeight;
}
return height +1;
}
Here is full code:
public class MorseCodeTree {
private static BSTElement<String, MorseCharacter> rootElement;
public BSTElement<String, MorseCharacter> getRoot() {
return rootElement;
}
public static void setRoot(BSTElement<String, MorseCharacter> newRoot) {
rootElement = newRoot;
}
public MorseCodeTree(BSTElement<String,MorseCharacter> element) {
rootElement = element;
}
public MorseCodeTree() {
rootElement = new BSTElement("Root", "", new MorseCharacter('\0', null));
}
public int getHeight() {
return getHeight(this.getRoot());
}
private int getHeight(BSTElement<String,MorseCharacter> element) {
if (element == null) {
return -1;
} else {
int leftHeight = getHeight(element.getLeft());
int rightHeight = getHeight(element.getRight());
if (leftHeight < rightHeight) {
return rightHeight + 1;
} else {
return leftHeight + 1;
}
}
}
public static boolean isEmpty() {
return (rootElement == null);
}
public void clear() {
rootElement = null;
}
public static void add(BSTElement<String,MorseCharacter> newElement) {
BSTElement<String, MorseCharacter> target = rootElement;
String path = "";
String code = newElement.getKey();
for (int i=0; i<code.length(); i++) {
if (code.charAt(i)== '.') {
if (target.getLeft()!=null) {
target=target.getLeft();
} else {
target.setLeft(newElement);
target=target.getLeft();
}
} else {
if (target.getRight()!=null) {
target=target.getRight();
} else {
target.setRight(newElement);
target=target.getRight();
}
}
}
MorseCharacter newMorseChar = newElement.getValue();
newElement.setLabel(Character.toString(newMorseChar.getLetter()));
newElement.setKey(Character.toString(newMorseChar.getLetter()));
newElement.setValue(newMorseChar);
}
public static void main(String[] args) {
MorseCodeTree tree = new MorseCodeTree();
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
while (line != null) {
String[] output = line.split(" ");
String letter = output[0];
MorseCharacter morseCharacter = new MorseCharacter(letter.charAt(0), output[1]);
BSTElement<String, MorseCharacter> bstElement = new BSTElement(letter, output[1], morseCharacter);
tree.add(bstElement);
line = reader.readLine();
System.out.println(tree.getHeight());
}
reader.close();
} catch (IOException e) {
System.out.println("Exception" + e);
}
There doesn't appear to be anything significantly wrong1 with the code that you have shown us.
If this code is giving a StackOverflowException for a small tree, that most likely means that your tree has been created incorrectly and has a cycle (loop) in it. If your recursive algorithm encounters a cycle in the "tree" it will loop until the stack overflows2.
To be sure of this diagnosis, we need to see an MVCE which includes all code needed to construct an example tree that exhibits thie behavior.
1 - There is possibly an "off by one" error in the height calculation, but that won't cause a stack overflow.
2 - Current Java implementations do not do tail-call optimization.
My program stops after the first element gets into array. Could you help me? Here's the code:
sorry for that
i've made some changes now ArrayQueue is my class where all my methods are implemented
QueueElement is another class that holds the type of element..
i think the problem now is at the ArrayQueue class
import java.io.*;
import java.util.Scanner;
public class QueueTest
{ private static Scanner scan =new Scanner(System.in);
public static void main(String[] args)
{
ArrayQueue queue = new ArrayQueue();
System.out.println("insert :" +
" P: to print the array "+
"S: to sort "+
"E: to empty");
do
{
if (userInput.startsWith("Y")) {
System.out.println("insert the value of element");
int vl = scan.nextInt();
System.out.println("insert the description");
String p = scan.next();
System.out.println("insert true or false");
boolean vlf = scan.nextBoolean();
queue.shtoElement(new QueueElement(vl, p, vlf));
} else if (userInput.startsWith("P")) {
queue.shfaqArray();//display the array
} else if (userInput.startsWith("S")) {
queue.rendit();//sort the array
} else if (userInput.startsWith("E")) {
queue.Empty();//empty array
}
System.out.println("Insert:" + " P: to display the array "
+ " S: to sort array "
+ " E: to empty");
userInput = scan.next();
} while (!userInput.equalsIgnoreCase("exit"));
}
}
here is the class ArrayQueue
public class ArrayQueue implements Queue
{
//build the queue
QueueElement[] tabela= new QueueElement[MADHESIA];
QueueElement element= new QueueElement();
//test if queue is empty
public boolean isEmpty()
{
boolean empty = true;
for(int k =0;k<tabela.length;k++)
{
if(tabela[k] !=null)
empty =false;
break;
}
return empty;
}
public boolean isFull()
{
boolean full=false;
for(int k=0;k<tabela.length;k++)
{
if(tabela[k]!=null)
full=true;
break;
}
return full;
}
//sort the array
public void rendit()
{
QueueElement temp=tabela[0];
for(int i=0;i<tabela.length;i++)
{
for(int j=i+1;j<tabela.length;j++)
if(tabela[j]!=null)
{
if(tabela[j].compareTo(tabela[i])==1)
{
tabela[j]=temp;
tabela[i]=tabela[j];
temp=tabela[i];
}
else
{
nrElementeve++;
}
}
if(tabela[i].getVlefshmeria()==false)
{
hiqElement(i,temp);
}
}
}
// add element into the array
public void shtoElement(QueueElement el)
{
if(isEmpty())
{
tabela[0]=el;
}
else
{
for(int i=0;i<tabela.length;i++)
{
if(tabela[i]!= null && (el.compareTo(tabela[i])==0))
{
System.out.println("element can't be added into array cause it exists !");
}
{
if(isFull())
{
int index=tabela.length;
tabela=rritMadhesine(tabela);
tabela[index]=el;
}
else
{
for(int j=0;j<tabela.length;j++)
{
if(tabela[j]==null)
tabela[j]=el;
break;
}
}
}
}
}
}
//find max of array
public QueueElement gjejMax()
{
QueueElement max = tabela[0];
for (QueueElement element :tabela)
{
if(element.getValue() > max.getValue())
{
max =element;
}
return max;
}
return max;
}
//find min of array
public QueueElement gjejMin()
{
QueueElement min= tabela[0];
for(QueueElement element : tabela)
{
if(element.getValue()< min.getValue())
{
min=element;
}
return min;
}
return min;
}
//remove element from array
public void hiqElement(int indeksi, QueueElement temp)
{
if(tabela.length > 0)
{
if(gjejMax().compareTo(temp)==0 || gjejMin().compareTo(temp)==0)
{
System.out.println("element can't be removed!");
}
else
{
for(int i=indeksi;i<tabela.length;i++)
{
tabela[i]=tabela[i+1];
}
}
nrElementeve--;
}
}
//empty array
public void Empty()
{
tabela= new QueueElement[MADHESIA];
}
//display the array
public void shfaqArray()
{
for(int i=0;i< tabela.length;i++)
{
if(tabela[i]!=null)
{
System.out.println(tabela[i]);
}
else
break;
}
}
//increase the length of array
public static QueueElement [] rritMadhesine(QueueElement[] array){
QueueElement[] tab=new QueueElement[array.length+2];
return tab;
}
private int nrElementeve;
private static final int MADHESIA = 10;
}
Don't know what ArrayQueue and QueueElement are, but...
It seems like you're reading user input then going through a decision tree to decide what to do based on that input. But at each point, you are re-reading the user input:
if(scan.next().startsWith("Y"))
{
System.out.println("Jepni vleren e elem");
vl=scan.nextInt();
System.out.println("Jepni pershkrimin e elem");
p=scan.next();
System.out.println("Jepni vlefshmerine e elem");
vlf=scan.nextBoolean();
queue.shtoElement(new QueueElement(vl,p,vlf));
}
else
{
if(scan.next().startsWith("P"))
queue.shfaqArray();
}
if(scan.next().startsWith("E"))
queue.Empty();
if(scan.next().startsWith("S"))
queue.rendit();
else
{
break;
}
I think you want something more like:
String userInput = scan.next();
if(userInput.startsWith("Y"))
{
System.out.println("Jepni vleren e elem");
vl=scan.nextInt();
System.out.println("Jepni pershkrimin e elem");
p=scan.next();
System.out.println("Jepni vlefshmerine e elem");
vlf=scan.nextBoolean();
queue.shtoElement(new QueueElement(vl,p,vlf));
}
else if(userInput.startsWith("P"))
queue.shfaqArray();
else if(userInput.startsWith("E"))
queue.Empty();
else if(userInput.startsWith("S"))
queue.rendit();
else
{
break;
}
Where you read the user input once (String userInput = scan.next();) and then decide what to do based on the userInput variable and not re-scan each time. Also, it looks like you might be missing a couple of else statements somewhere in the middle there.
I have a program that creates a queue, enqueues objects to the queue and then dequeues them one by one if the queue is not empty. The problem I am having is that the queue comes up empty each time it is checked. Print is called on the queue after enqueuing each object and it prints the queue's contents just fine.
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);
}
}
}
there doesn't seem to be anything wrong with the queue's isEmpty() method, but here it is:
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 you change if (var=true) to if(var==true) or just if(var) you should see a different result