扫描仪从文件中跳过每隔一行
我正在尝试扫描文本文件并将每一行放入一个arraylist,并在下一行是’*’时停止扫描,但是,我的arraylist存储每一行,我不知道为什么。
Scanner scan = new Scanner(new File("src/p/input2.txt")); ArrayList words = new ArrayList(); 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中:
[浸,疯,枫,垫,豆荚,树液,切片,香料,股票]
你总是读两行(除非你得到*
)
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);
你正在阅读它两次。
存放,使用它。
while(scan.hasNextLine()) { String str = null; if((str =scan.nextLine()).equals("*")) break; words.add(str);//here you are not reading again. }
试试这个,
Scanner scan = new Scanner(new File("src/p/input2.txt")); ArrayList words = new ArrayList (); while(scan.hasNextLine()) { String readLine = scan.nextLine(); if(readLine.equals("*")) { // if you want just skip line then use use continue-keyword // continue; // if you want just stop parsing then use use break-keyword break; } words.add(readLine); }
每次调用scan.nextLine()时,扫描仪都会移动到下一行。 你在循环中调用它两次(第一次检查,第二次添加)。 这意味着您检查一行并添加下一行。
解决方案是将其调用一次并将其存储在变量中:
while(scan.hasNextLine()) { String str = scan.nextLine(); if(str.equals("*")) break; words.add(str); }
问题在这里:
while(scan.hasNextLine()) { if(scan.nextLine().equals("*")) break; words.add(scan.nextLine()); // --> You are reading two time in same loop }
因此,不要读取两次,只需使用临时变量来存储值,然后在循环中使用该临时变量。
您可以使用以下代码:
while(scan.hasNextLine()) { String temp = scan.nextLine(); if(temp.equals("*")) break; words.add(temp); }