1

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

The textfile:

1

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

What is being stored in my arraylist:

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

Radiodef
  • 35,285
  • 14
  • 78
  • 114
Arthur
  • 1,339
  • 3
  • 15
  • 36
  • @vishalgajera skip it, I am storing the the next lines as pairs successfully, just an issue with the first set of words – Arthur Nov 26 '15 at 05:42

5 Answers5

2

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);
TheLostMind
  • 34,842
  • 11
  • 64
  • 97
1

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.
}
Uma Kanth
  • 5,614
  • 2
  • 16
  • 40
1

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);
}
Vishal Gajera
  • 3,798
  • 3
  • 23
  • 49
1

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);
}
Breeze
  • 1,824
  • 2
  • 30
  • 37
1

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);
    }
Ashish Ani
  • 314
  • 1
  • 7