首页 > 解决方案 > Java - 将文件中的所有整数添加到 ArrayList

问题描述

我正在尝试将文件中的所有整数读取到 java JUnit 测试的 @BeforeClass 中的 ArrayList 中。出于测试目的,我只是尝试将 arraylist 的所有值打印到屏幕上。然而没有任何输出。任何投入将不胜感激。

public class CalcAverageTest
{

static List<Integer> intList = new ArrayList<Integer>();

@BeforeClass
public static void testPrep() {
    try {
        Scanner scanner = new Scanner(new File("gradebook.txt"));
        while (scanner.hasNextInt()) {
            intList.add(scanner.nextInt());

        }
        for (int i=0;i<intList.size();i++) {
            System.out.println(intList.get(i));
        }
    } catch (IOException e) {
        e.printStackTrace();   
    } catch (NumberFormatException ex) {
        ex.printStackTrace();
    }            
 }
}

标签: javajunitjava.util.scanner

解决方案


您需要遍历文件直到最后一行,因此您需要更改循环中的条件并使用.hasNextLine()而不是.nextInt()

while (scanner.hasNextLine()) {
    String currLine = scanner.nextLine();
    if (currLine != null && currLine.trim().length() > 0 && currLine.matches("^[0-9]*$"))
        intList.add(Integer.parseInt(currLine));
    }
}

在这里,我们读取每一行并将其存储在currLine. 现在只有当它包含一个数值时它才会被添加到intList它被跳过的 else 中。^[0-9] $* 是用于仅匹配数值的正则表达式。

从文档中,hasNextLine()

如果此扫描仪的输入中有另一行,则返回 true。此方法可能会在等待输入时阻塞。扫描仪不会超过任何输入。


推荐阅读