gpt4 book ai didi

java - 使用时钟 while 循环在 while 循环中读取文件

转载 作者:太空宇宙 更新时间:2023-11-04 10:58:45 30 4
gpt4 key购买 nike

目前正在学习数据结构类(class),我们将在下一个程序中使用队列。

我们得到一个输入文件,如下所示:

10 324 Boots 32.33
11 365 Gloves 33.33
12 384 Sweater 36.33
13 414 Blouse 35.33

我要读取第一个 int (这是一个时间单位)并将其用作在后台运行的时钟的引用。

我做了一些事情:

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。之后调用。

稍后当您读取 typeitemPrice 时,您会再次遇到完全相同的问题。

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();
}

关于java - 使用时钟 while 循环在 while 循环中读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47125629/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com