Reading integers from file into an arraylist

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.

Answers


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

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.


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.


Need Your Help

Empty test suite and custom package name

android junit android-gradle build.gradle android-espresso

I have an app with flavorDimensions and productFlavors and I am customising the package name of Trial variants with the build.gradle script as follows: