3
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;

public class Test
{
public static void main (String args[]) throws java.io.IOException
    {
    Scanner s = new Scanner(new File("filepath"));
    ArrayList<Integer> list = new ArrayList<Integer>();
    while (s.hasNext()){
        if(s.hasNextInt()){
            list.add(s.nextInt());
        }
    }
    s.close();
    System.out.println(list);
    }
}

I'm trying to read only integers from a text file that has the following format per line: text integer text.

This is what I have so far but when I compile and run it prints never ending [] for whatever reason.

Please note that I changed the filepath just for uploading it to here, that is not the issue.

Touchstone
  • 5,575
  • 7
  • 41
  • 48
user3386295
  • 57
  • 2
  • 6

3 Answers3

3

When I compile and run it prints never ending

This loop is the culprit:

while (s.hasNext()){
    if(s.hasNextInt()){
        list.add(s.nextInt());
    }
}

Consider what happens when the scanner hasNext, but whatever that next token is, it is not an int. In this case your loop becomes infinite, because the body of the loop does not consume anything, leaving the scanner in exactly the same state where it was at the beginning of the loop.

To fix this problem, add an else to your if, read s.next(), and ignore the result:

while (s.hasNext()){
    if(s.hasNextInt()){
        list.add(s.nextInt());
    } else {
        s.next();
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Try this:

import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;

public class Test
{
    public static void main (String args[]) throws java.io.IOException
    {
        Scanner s = new Scanner(new File("filepath"));
        ArrayList<Integer> list = new ArrayList<Integer>();
        while (s.hasNext()){
            list.add(s.nextInt());
            s.nextLine(); // Eat the next line
            // Remove the conditional if statement to eat the new line
        }
        System.out.println(list);
        s.close();
    }
}

You have to direct the reader head to move past the line and then the hasNext() function will determine if there is any new content.

Abdullah Bakhsh
  • 658
  • 1
  • 9
  • 15
0

Problem is with this block

while (s.hasNext()){
    if(s.hasNextInt()){
        list.add(s.nextInt());
    }
}

what you should do in order to read the specified format is:

while (s.hasNext()){
    String line = s.nextLine();
    String[] content = line.split(" ");
    list.add(Integer.parseInt(content[1]));
}

Hope this helps.

Sanjeev
  • 9,876
  • 2
  • 22
  • 33