java - 在每行包含特定信息的文件中读取有点麻烦
问题描述
所以我在读取文件时遇到问题。该文件在第一行包含 2 个整数,文件的其余部分在单独的行中包含字符串。出于某种原因,我在这段代码中的逻辑似乎没有正确使用文件中的每一行。我试图通过打印出正在发生的事情来解决这个问题,似乎第二个 nextLine() 甚至没有执行。
while(inputFile.hasNext())
{
try
{
String start = inputFile.nextLine();
System.out.println(start); // tried to troubleshoot here
String [] rowsAndCols = start.split(" "); // part where it should read the first two integers
System.out.println(rowsAndCols[0]); // tried to troubleshoot here
int rows = Integer.parseInt(rowsAndCols[0]);
int cols = Integer.parseInt(rowsAndCols[1]);
cell = new MazeCell.CellType[rows+2][cols+2];
String mazeStart = inputFile.nextLine(); // part where it should begin to read the rest of the file containing strings
String [] mazeRowsAndCols = mazeStart.split(" ");
MazeCell.CellType cell2Add;
解决方案
根据您上面的描述,只有第一行包含整数,因此您的 while 循环是错误的,因为它试图将每一行转换为整数。
拆分成代码成
if (inputFile.hasNextLine())
{
String start = inputFile.nextLine();
String [] rowsAndCols = start.split(" "); // part where it should read the first two integers
int rows = Integer.parseInt(rowsAndCols[0]);
int cols = Integer.parseInt(rowsAndCols[1]);
}
然后是字符串读取的while循环
推荐阅读
- python - 如何在 python dm-script 中获取当前文件路径
- android - 如何从 Retrofit、RxJava、Android 中的所有请求中发出多个请求和响应
- python - 如何在python中解决geopandas执行问题?
- html - 我们可以在 url - django 中传递两个参数吗?
- git - Git merge reverted, not merge all files in future merge
- javascript - ASP.NET Core - 如何将 Javascript 变量从视图传递到控制器
- java - 链接上的反向 ArrayList
- r - 尝试使用 dplyr 仅滞后一些变量
- python - Tkinter 调用函数时显示图片
- python - Python 'int' 对象不可下标 - 转换无法按预期工作