hasextdouble 没有读取文件中的下一个替身

hasnextdouble not reading my next double in a file

您好,我在使用扫描仪方法时遇到了问题 hasNextDouble()。 我的代码从一个文件中读取并创建一个 Vehicle 对象,将其添加到一个数组中。车辆 class 有一个名为 OversizedVehicle 的子 class,还有一个额外的 double 字段来指示其高度。这就是我使用 if (hasNextDouble()) 的原因,因此如果扫描器读取 double,它将创建一个 OversizedVehicle 对象而不是 Vehicle。这是我的代码:

while(s1.hasNext()) 
    {
            regNo = s1.next();
            make = s1.next();
            year = Integer.parseInt(s1.next());
            description = s1.next();
            if(s1.hasNextDouble() == true) {
            height = s1.nextDouble();
            vehicle = new OversizedVehicle(regNo,make,year,description,height);
            }
            else {
            vehicle = new Vehicle(regNo, make, year, description);
            }
            System.out.println("New vehicles from file added to array in position " + count);
            vehicles[count] = vehicle;
            count++;
    }

我正在使用 Eclipse IDE,当我在调试模式下 运行 时,if 语句的计算结果总是 true,错误地将下一个 [=21] =] 在 height 变量的输入中。即使在输入中这个值不是 double,而是 int。我不确定出了什么问题。

在我看来,您的输入包含 车辆超大型车辆 的参数,它们的参数数量不同:车辆有 4参数,超大车有5个,大概是这样:

1 Toyota 2015 sedan 2 Toyota 2016 truck 2.1 3 Toyota 2015 mini ...

等等。我猜这是因为你似乎在说 s1.hasNextDouble() 总是正确的, 它会导致 "the variable regNo to be initialised into a double"。 例如,当扫描器在上面的示例中读取 "sedan" 时,可能会发生这种情况, 下一个标记是“2”, 由于“2”可以是有效的 doubles1.hasNextDouble() return是真的。 换句话说,当下一个标记是双精度或整数时,s1.hasNextDouble() 将为真。

您可以通过检查 s1.hasNextInt() 来区分这些情况, 因为这将 return false 用于 doubletrue 用于 int.

while (scanner.hasNext()) {
  String regNo = scanner.next();
  String make = scanner.next();
  int year = scanner.nextInt();
  String description = scanner.next();

  if (scanner.hasNext() && !scanner.hasNextInt()) {
    double height = scanner.nextDouble();
    vehicle = new OversizedVehicle(regNo, make, year, description, height);
  } else {
    vehicle = new Vehicle(regNo, make, year, description);
  }

  // ...
}

这应该适用于上面的示例。 但是如果你的数据是逐行的, 那么我建议依靠行分隔符来区分记录, 它将使实现更加简单明了。

while (scanner.hasNext()) {
  String line = scanner.nextLine();
  String[] parts = line.split(" ");
  String regNo = parts[0];
  String make = parts[1];
  int year = Integer.parseInt(parts[2]);
  String description = parts[3];

  if (parts.length == 5) {
    double height = scanner.nextDouble();
    vehicle = new OversizedVehicle(regNo, make, year, description, height);
  } else {
    vehicle = new Vehicle(regNo, make, year, description);
  }

  // ...
}