Reading integers from file into an arraylist

与世无争的帅哥 提交于 2019-12-30 07:09:53

问题


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.


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/22213916/reading-integers-from-file-into-an-arraylist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!