我在文件中有两种不同的输入。 第一行包含必须创建的任务数,然后下一行具有每个任务必须具有的数据,例如,假设文件具有
4
Task1 4, 5
Task2 2, 7
Task3 8, 9
Task4 7, 2
//followed by other data
我想为任务创建一个数组,然后读取每个任务必须包含的信息。 所以我尝试了:
Scanner inFile = new Scanner(new File("Readthis.txt"));
int numberOfTasks =inFile.nextInt();
Tasks myTasks = Tasks[numberOfTasks];
for (int i=0;i<numberOfTasks;i++)
{
String line = inFile.nextLine();
String[] temp = line.split(" ");
String TaskName = temp[0];
int TaskDuration = Integer.valueof(temp[1]);
//and the other process for the third number
}
我的问题是,它将任务数设置为4,没问题,但是,在启动“ for”循环时,它将行读为“”,而不是“ Task1 4 5”,依此类推,>
所以现在它会抛出异常,因为temp [0]为空,但是它应该是任务的名称。
扫描仪不应该继续阅读它停下来的地方吗?读完第一个“ 4”之后?我很困惑。
如何使其按需工作?
答案 0 :(得分:2)
您不应使用nextInt()而是使用nextLine()逐行读取文件。
尝试用以下内容替换nextInt()行:
int numberOfTasks =Integer.parseInt(inFile.nextLine());
代码将读取整行(在示例中包含4个数字),并将尝试将其解析为Integer。
nextInt()将读取下一个标记,而不是整行,因此,在nextInt()读取4个数字之后,剩下的新行字节(\ n)供nextLine()读取。
public int nextInt()
将输入的下一个标记扫描为int。
...