简体   繁体   English

扫描仪使用循环从命令行读取文本文件,但循环不会中断

[英]Scanner reading a text file from command line using a loop, but the loop will not break

So I want to read in a .text or a .data file in java from the commandline using所以我想从命令行使用 java 读取 .text 或 .data 文件

java name < filename.data

Here is the code:这是代码:

        ArrayList<String> input = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLine()) {
             System.out.println("Reading line");
             String line = scanner.nextLine().trim();
             System.out.println("The line is: " + line);
             if (line.equals("") || line.isEmpty()) {
                 System.out.println("Found blank area");
                  break;
              }  
             System.out.println("Adding to arrayList");
             input.add(line);

        }
        System.out.println("Read in was successful");

The line "system.out.println("Read in was successful"); is never reached. It seems the 'if' statement used to break the loop after reading is also never reached. It doesn't even seem that the loop returns to the top. This is my output (the method does successfully read in all my text file) “system.out.println("Read in was successfully"); 行从未到达过。似乎用于在读取后中断循环的“if”语句也从未到达过。循环似乎也没有返回到顶部。这是我的输出(该方法确实成功读取了我的所有文本文件)

Reading line
The line is: car
Adding to arrayList
Reading line
The line is: mega
Adding to arrayList
Reading line
The line is: bed
Adding to arrayList
Reading line
The line is: stop
Adding to arrayList
Reading line
The line is: game
Adding to arrayList
Reading line
The line is: pots
Adding to arrayList
Reading line
The line is: arc
Adding to arrayList

I would expect one more run which indicates that the program has reached the end of the file by printing out "Found blank area".我希望再运行一次,通过打印出“找到的空白区域”来表明程序已到达文件末尾。

So it seems to successfully read line, but cannot seem to break.所以它似乎成功地读取了行,但似乎无法打破。 My program doesn't crash, it just "hangs" there if that makes any sense.我的程序没有崩溃,它只是“挂”在那里,如果有任何意义的话。

It's not reaching if (line.equals("") || line.isEmpty()) code as I think there is no empty lines in the empty file ,I tried to ran the code and got desired output with input file content as它没有达到if (line.equals("") || line.isEmpty())代码,因为我认为空文件中没有空行,我尝试运行代码并获得所需的输出,输入文件内容为

Output输出

Reading line
The line is: car
Adding to arrayList
Reading line
The line is: mega
Adding to arrayList
Reading line
The line is: bed
Adding to arrayList
Reading line
The line is: stop
Adding to arrayList
Reading line
The line is: game
Adding to arrayList
Reading line
The line is: pots
Adding to arrayList
Reading line
The line is:
Found blank area
Read in was successful

Input file输入文件

car
mega
bed
stop
game
pots

arc

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

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