Java – different output of ‘run’ and ‘debug’ when using readline()

I get two different outputs of the same code When I debug and step through each line (using NetBeans 8.1), I get a result When I run the code once, I get different results

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

In both cases, the first line of code should be printed first But it only does this when I run the code

If I debug the code and step through each line, print the second line

Why is that?

Update: the following is a debug screenshot Now, if I skip it, I will execute system out. Println line As you can see on the right, STR contains' second '

Solution

Does the IDE evaluate file. When debugging readLine()? In eclipse, you can define a "monitor expression" to do this

This may explain your problem, because when you walk through the code line by line, only one line defines the file, so you can evaluate the above expression Therefore, the second is output instead of the first

Update: now you've added a screenshot, which is obvious This is partly the fault of netbean developers, because they chose "variables" in the title, which is misleading, because evaluating variables has no side effects, and evaluating arbitrary expressions (such as file. Readline()) obviously has

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>