【问题标题】:Using a clock while loop to read files in a while loop使用时钟while循环在while循环中读取文件
【发布时间】:2018-04-17 22:45:16
【问题描述】:

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

我们得到了一个像这样的输入文件:

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”错误。我知道您需要在字符串之前跳过马车,这就是我相信我正在做的事情。

我不知道从这里去哪里。

【问题讨论】:

  • 你的错误在于 type = infp.nextLine()。它读取整行。您应该使用 read line 读取您的行并使用 String split 方法。

标签: java loops while-loop java.util.scanner clock


【解决方案1】:

因此,鉴于这些列:

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

【讨论】:

    猜你喜欢
    • 2011-03-05
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 2021-04-05
    • 1970-01-01
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多