简体   繁体   English

当队列中有数据时,为什么我的输出打印为空?

[英]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. 我正在尝试获取一个程序,以基于两个范围变量将答案打印出x次。 I created a queue variable that will hold an equation before it enters my for loop. 我创建了一个队列变量,该变量将在进入for循环之前保存方程式。 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. 在我的for循环中,我创建了队列的备份版本,因为当我将其发送到另一个方法时,它将从该队列中删除值,最终使我留下一个空队列。 I use that backup in the method and then just redeclare it to the original queue at the top of the for loop. 我在方法中使用该备份,然后将其重新声明为for循环顶部的原始队列。

My problem is, it works once giving me the desired output, however, each time after, it prints out null. 我的问题是,一旦给我所需的输出,它就会工作,但是,每次之后,它都会打印出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

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. 您对result所做的任何更改都会反映在backup_result ,反之亦然。 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. 这只是问题之一...另一个问题是,如果您需要将队列复制到备份中,那么您正在考虑错误的队列方式:它们是为将代码放入其中的一部分而设计的,以及另一个删除它们并对其进行处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM