简体   繁体   中英

Different output for 'run' and 'debug' when using readline()

I get two different output for the same code. I get one result when I debug and step through every line (using Netbeans 8.1). And I get a different result when I run the code all at once.

This is the code,

public class Testing {
    public static void main(String... args) throws IOException {
        BufferedReader file = new BufferedReader(new FileReader("input"));
        String str = file.readLine();
        System.out.println(str);
    }
}

This is the input file

first
second
third
fourth

The code should print the first line first in both cases. But it does that only when I run the code.

If I debug the code and step through every line, the second line second is printed.

Why is this happening?

Update: The following is a debugging screenshot. Right now, if I step over it will execute the System.out.println line. As you can see on the right side, str contains 'second'.

在此输入图像描述

Does your IDE evaluate file.readLine() while you are debugging? In Eclipse, one can define “watch expressions” that do exactly this.

This might explain your problem, since when you step through the code line by line, there is exactly one line in which file is defined and therefore the expression above can be evaluated. Therefore the output of second instead of first .

Update: Now that you added the screenshot, it's clear. It's partly the Netbean developer's fault, since they chose “Variables” at the headline, which is misleading, since evaluating variables does not have a side-effect, while evaluating arbitrary expressions (like file.readLine() ) clearly has.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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