扫描仪从文件中每隔一行跳过一次 [英] Scanner skipping every second line from file

查看:141
本文介绍了扫描仪从文件中每隔一行跳过一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试扫描文本文件并将每一行放入arraylist,并在下一行为'*'时停止扫描,但是,我的arraylist存储每一行​​,我不知道为什么。

I'm trying to scan a text file and place each line into an arraylist, and stop scanning when the next line is a '*', however, my arraylist is storing every 2nd line and I am not sure why.

Scanner scan = new Scanner(new File("src/p/input2.txt"));
ArrayList<String> words = new ArrayList<String>(); 

while(scan.hasNextLine()) { 
    if(scan.nextLine().equals("*"))
        break;
    words.add(scan.nextLine());
}

文本文件:

1

dip
lip
mad
map
maple
may
pad
pip
pod
pop
sap
sip
slice
slick
spice
stick
stock
*
spice stock
may pod

什么是存储在我的arraylist中:

What is being stored in my arraylist:


[dip,mad,maple,pad,pod,sap,slice,spice,stock]

[dip, mad, maple, pad, pod, sap, slice, spice, stock]


推荐答案

你总是读两行(除非你得到 *

You are always reading the line twice (unless you get a *)

if(scan.nextLine().equals("*")) // read here - "someString"
   break;
words.add(scan.nextLine());  // ignore last read line and read again.

您只读一次然后比较。

String value = scan.nextLine();
// check for null / empty here
if (value.equals("*"))
  break;
words.add(value);

这篇关于扫描仪从文件中每隔一行跳过一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆