将文件中的整数读入数组列表 [英] Reading integers from file into an arraylist

查看:29
本文介绍了将文件中的整数读入数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

要解决此问题,请在您的 if 中添加 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();
    }
}

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

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