使用时钟while循环在while循环中读取文件
Using a clock while loop to read files in a while loop
目前正在学习我的数据结构class,我们将在下一个程序中使用队列。
我们得到了一个这样的输入文件:
10 324 Boots 32.33
11 365 Gloves 33.33
12 384 Sweater 36.33
13 414 Blouse 35.33
我要读取第一个 int(这是一个时间单位)并将其用作我的时钟的参考,该时钟在后台保持 运行ning。
我按照这些思路做了一些事情:
Scanner infp = new Scanner(new File(FILE));
while (busy) {
clock = 0;
clock += clockCount++;
while (infp.hasNext()) {
timeEntered = infp.nextInt();
infp.nextLine();
System.out.println(timeEntered);
busy = true;
if (timeEntered == clock) {
itemNum = infp.nextInt();
type = infp.nextLine();
itemPrice = infp.nextDouble();
}
}
}
问题是,当我 运行 它时,我得到一个 'InputMismatchException' 错误。我知道您需要在字符串之前跳过回车,我相信我正在这样做。
我不知道从这里到哪里去。
鉴于这些列:
10 324 Boots 32.33
11 365 Gloves 33.33
12 384 Sweater 36.33
13 414 Blouse 35.33
对于每一行,您将第一列读入 timeEntered
。
然后你做了 infp.nextLine()
,这是一个错误。
当您调用 nextLine
时,扫描器会读取当前行中所有未读的内容,直到结尾。
这意味着您无法读取其他列值。
但是你需要它们。因此,当您仍想处理一行上的值时,请不要调用 nextLine
。之后调用它。
稍后当您阅读 type
和 itemPrice
时,您又遇到了完全相同的问题。
将 while (infp.hasNext())
替换为:
while (infp.hasNextLine()) {
int timeEntered = infp.nextInt();
System.out.println(timeEntered);
busy = true;
if (timeEntered == clock) {
itemNum = infp.nextInt();
type = infp.next();
itemPrice = infp.nextDouble();
}
infp.nextLine();
}
目前正在学习我的数据结构class,我们将在下一个程序中使用队列。
我们得到了一个这样的输入文件:
10 324 Boots 32.33
11 365 Gloves 33.33
12 384 Sweater 36.33
13 414 Blouse 35.33
我要读取第一个 int(这是一个时间单位)并将其用作我的时钟的参考,该时钟在后台保持 运行ning。
我按照这些思路做了一些事情:
Scanner infp = new Scanner(new File(FILE));
while (busy) {
clock = 0;
clock += clockCount++;
while (infp.hasNext()) {
timeEntered = infp.nextInt();
infp.nextLine();
System.out.println(timeEntered);
busy = true;
if (timeEntered == clock) {
itemNum = infp.nextInt();
type = infp.nextLine();
itemPrice = infp.nextDouble();
}
}
}
问题是,当我 运行 它时,我得到一个 'InputMismatchException' 错误。我知道您需要在字符串之前跳过回车,我相信我正在这样做。
我不知道从这里到哪里去。
鉴于这些列:
10 324 Boots 32.33
11 365 Gloves 33.33
12 384 Sweater 36.33
13 414 Blouse 35.33
对于每一行,您将第一列读入 timeEntered
。
然后你做了 infp.nextLine()
,这是一个错误。
当您调用 nextLine
时,扫描器会读取当前行中所有未读的内容,直到结尾。
这意味着您无法读取其他列值。
但是你需要它们。因此,当您仍想处理一行上的值时,请不要调用 nextLine
。之后调用它。
稍后当您阅读 type
和 itemPrice
时,您又遇到了完全相同的问题。
将 while (infp.hasNext())
替换为:
while (infp.hasNextLine()) {
int timeEntered = infp.nextInt();
System.out.println(timeEntered);
busy = true;
if (timeEntered == clock) {
itemNum = infp.nextInt();
type = infp.next();
itemPrice = infp.nextDouble();
}
infp.nextLine();
}