【问题标题】:Java.util.scanner only seems to be reading certain linesJava.util.scanner 似乎只读取某些行
【发布时间】:2018-04-03 14:59:14
【问题描述】:

我正在编写一个程序(根据规范),它读取一个文件并使用它来模拟仓库中的机器人。我使用扫描仪读取文件并使用 switch 语句执行正确的操作,但仅执行某些情况。

这是我遇到问题的代码:

private static void readFromFile() {

        Scanner input = null;

        float capacity = 0;
        float chargeSpeed = 0;

        try {
            input = new Scanner(
                    new File("C:\\Users\\User\\Documents\\Uni\\Java Projects\\Kiva\\configs\\twoRobots.sim"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        while (input.hasNextLine()) {
            String line = input.nextLine();
            String[] arr = line.split("\\s+"); //regex for whitespace

switch (arr[0]) {
            case "format":
                System.out.println(arr[0]);
                break;
            case "width":
                System.out.println(arr[0]);
                break;
            case "height":
                System.out.println(arr[0]);
                break;
            case "capacity":
                System.out.println(arr[0]);
                break;
            case "chargeSpeed":
                System.out.println(arr[0]);
                break;
            case "podRobot":
                System.out.println(arr[0]);
                break;
            case "shelf":
                System.out.println(arr[0]);
                break;
            case "station":
                System.out.println(arr[0]);
                break;
            case "order":
                System.out.println(arr[0]);
                break;
            }

            line = input.nextLine();
        }

这是文件(tworobots.sim):

format 1
width 4
height 4
capacity 50
chargeSpeed 1
podRobot c0 r0 3 1
podRobot c1 r1 3 3
shelf ss0 2 2
station ps0 0 2
order 13 ss0

这是输出(应列出所有操作):

format
height
chargeSpeed
podRobot
station
order

这是为什么?任何帮助将不胜感激。

【问题讨论】:

  • 尝试在循环结束时删除line = input.nextLine();

标签: java switch-statement java.util.scanner


【解决方案1】:

问题出在这段摘录中:

while (input.hasNextLine()) {
        String line = input.nextLine();
        String[] arr = line.split("\\s+"); //regex for whitespace

    switch (arr[0]) {
           //...
        }

        line = input.nextLine(); // You read the next line and do nothing with it.
    }

所有行都被读取,但额外的nextLine 调用正在读取下一行,然后在循环开始后立即读取该行时什么也不做。只需删除第二个调用即可修复它。

【讨论】:

    【解决方案2】:

    多余的线出现在最后。

    line = input.nextLine(); // Remove this line in the end.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-29
      • 1970-01-01
      • 2018-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多