Scanner skipping every second line from file [duplicate]

坚强是说给别人听的谎言 提交于 2019-11-27 05:39:58

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.

You read only once and then compare.

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

You are reading it twice.

Store it, use it.

while(scan.hasNextLine()) { 
String str = null;
if((str =scan.nextLine()).equals("*"))
   break;
words.add(str);//here you are not reading again.
}

Try with this,

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);
}

Every time you call scan.nextLine() the scanner moves to the next line. You call it twice inside the loop (first time to check, second time to add). This means that you check one line and add the next one.

The solution is to call it one time and store it in a variable:

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

Problem is here :

while(scan.hasNextLine()) { 
        if(scan.nextLine().equals("*"))
            break;
        words.add(scan.nextLine()); // --> You are reading two time in same loop
    }

So instead of reading two times, Just use a temp variable to store value and use that temp variable in loop, afterwards.

You can use the following code:

while(scan.hasNextLine()) { 
        String temp = scan.nextLine();
        if(temp.equals("*"))
            break;
        words.add(temp);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!