l00kitsjake
l00kitsjake

Reputation: 1025

Why is my output printing null when the Queue has data?

I am trying to get a program to print out an answer to an equation x times based on two range variables. I created a queue variable that will hold an equation before it enters my for loop. In my for loop I created a backup version of the queue because when I send it to another method it removes values from that queue, eventually leaving me with an empty queue. I use that backup in the method and then just redeclare it to the original queue at the top of the for loop.

My problem is, it works once giving me the desired output, however, each time after, it prints out null. My guess is because it thinks the queue is empty but I dont understand why. Below is my code of my main file, should be enough.

public class Main {

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Infix Expression: ");
    String expression = keyboard.nextLine();
    GenericQueue<Token> result = new GenericQueue<Token>();

    Scanner keyboard2 = new Scanner(System.in);
    System.out.print("Range: ");
    String range = keyboard2.nextLine();

    int start = 0;
    int end = 5;
    String var = "x";

    Process.toPostfix(expression, result);

    for (int i=start; i<=end; i++) {
        GenericQueue<Token> backup_result = result;
        System.out.println(backup_result.toString());
        Rational answer = Process.evaluate(backup_result, i, var);
        System.out.println(i + "    " + answer);
    }

    keyboard.close();
    keyboard2.close();
    }
}

and here is my output:

    Infix Expression: (5+x)
Range: f
 5 x +
0    5

1    null

2    null

3    null

4    null

5    null

Upvotes: 0

Views: 803

Answers (1)

chiastic-security
chiastic-security

Reputation: 20520

When you write

GenericQueue<Token> backup_result = result;

you're not actually copying the queue, but just a reference to it. Any changes you make to result will be reflected in backup_result, and vice versa. You only ever have one queue, with two names.

This is only one of the problems... The other is that if you need to copy the queue into a backup then you're thinking the wrong way about queues: they're designed for one part of your code to put things into it, and another to remove them and deal with them.

Upvotes: 1

Related Questions