0

I am trying to skip the first and the last lines of a file and insert the rest of the information into an ArrayList. Here is what I have so farm to insert ALL elements from a file into an ArrayList.

 CodonSequence cs = new CodonSequence();
 try {
        Scanner scanner = new Scanner(new File("testSequence.txt"));
        while (scanner.hasNextLine()) {
            cs.addNucleotide(scanner.nextLine());
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
Mark Gold
  • 49
  • 1
  • 7

3 Answers3

0

Simply calling

scanner.nextLine();

once before any processing should do the trick.

At the end of your loop, do

 Scanner.nextLine();

Easiest is probably to enclose your data collection inside an if statement to check if the scanner.next() is not null:

  try {
            Scanner scanner = new Scanner(new File("testSequence.txt"));
            scanner.nextLine();//this would read the first line from the text file
            while (scanner.hasNextLine()) {
            if(!scanner.next().equals("")&&!scanner.next()==null){
                cs.addNucleotide(scanner.nextLine());
               }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
Abdul Manaf
  • 4,933
  • 8
  • 51
  • 95
0
 ArrayList<String> arrayList = new ArrayList<String>();
 BufferedReader reader = new BufferedReader(new FileReader(somepath));
 reader.readLine(); // this will read the first line
 String line1=null;
 while ((line1 = reader.readLine()) != null){ //loop will run from 2nd line until the end
        arrayList.add(scanner.nextLine());
 }

Im not sure what your CodonSequence is, but if you stored the 2nd until the last line in an ArrayList, you just remove the last element:

arrayList.remove(arrayList.size() - 1);

A few searching won't hurt.

BufferedReader to skip first line

Java - remove last known item from ArrayList

Hope this helps.

Community
  • 1
  • 1
jmcg
  • 1,547
  • 17
  • 22
0

I found a solution to my problem. I had to add:

scanner.nextLine();

before my while loop to skip the first line.

Mark Gold
  • 49
  • 1
  • 7