扫描程序每隔一行跳过文件



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

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

存储在我的数组列表中的内容:

【蘸料、疯料、枫、垫、荚、树液、切片、香料、高汤】

您总是读取该行两次(除非您得到*

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<String> words = new ArrayList<String>(); 
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);
    }

最新更新