将整数从文件读入arraylist [英] Reading integers from file into an arraylist

查看:138
本文介绍了将整数从文件读入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.

推荐答案


当我编译并运行时,打印永不结束

When I compile and run it prints never ending

这个循环是罪魁祸首:

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

考虑扫描仪 hasNext ,但无论下一个令牌是什么,它都不是 int 。在这种情况下,你的循环变得无限,因为循环的主体不消耗任何东西,使扫描器处于与循环开始时完全相同的状态。

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.

要解决此问题,请将 else 添加到,如果,请阅读 s.next (),并忽略结果:

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

这篇关于将整数从文件读入arraylist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆