java - 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();
}
}
}
解决方案
您需要遍历文件直到最后一行,因此您需要更改循环中的条件并使用.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。此方法可能会在等待输入时阻塞。扫描仪不会超过任何输入。
推荐阅读
- python - Flask/Python - 如何使用来自多个 IP 摄像机的实时镜头填充 HTML 页面?
- opentok - OpenTok 按钮来控制视频
- java - 带有参数和单引号的自定义 HQL 函数
- python - 检查两个字符串之间的顺序是否保持不变
- entity-framework - 如何解析实体框架中的特殊字符?
- python-3.x - AWS Lambda 中的 lxml 库
- python-3.x - 为什么我的递归函数没有连接字符串?
- react-native - iOS 上的 React Native:图像组件未从特定 URI 渲染图像
- javascript - 交换 Divs 然后在两个选择列表之间交换选定的选项值
- sql - 在 SQL Server 的视图创建脚本中使用变量