繁体   English   中英

读取数据并存入数组 Java

[英]Reading data and storing in array Java

我正在编写一个程序,允许用户在酒店预订房间(大学项目)。 我遇到了这个问题,当我尝试从文件中读取数据并将其存储在一个数组中时,我收到一个NumberFormatException

我已经在这个问题上停留了一段时间,无法弄清楚我哪里出错了。 我已经阅读了它,显然是当我尝试将字符串转换为数字时,但我无法弄清楚如何修复它。

请问有什么建议吗?

这是我的读者代码。

FileReader file = new FileReader("rooms.txt");
 Scanner reader = new Scanner(file);
 int index = 0; 
    
while(reader.hasNext()) {
    int RoomNum = Integer.parseInt(reader.nextLine());
    String Type = reader.nextLine();
    double Price = Double.parseDouble(reader.nextLine());
    boolean Balcony = Boolean.parseBoolean(reader.nextLine());
    boolean Lounge = Boolean.parseBoolean(reader.nextLine());
    String Reserved = reader.nextLine();
     rooms[index] = new Room(RoomNum, Type, Price, Balcony, Lounge, Reserved);
     index++;
    }
reader.close();

这是错误信息在此处输入图像描述

这是我试图读取的文件中的数据:

在此处输入图像描述

像这样改变你的while循环

while (reader.hasNextLine())
{ 
    // then split reader.nextLine() data using .split() function
    // and store it in string array
    // after that you can extract data from the array and do whatever you want
}

使用next()而不是nextLine()

您正在尝试将整行解析为 Integer。 您可以将整行读取为字符串,调用

。分裂(” ”)

在上面。 这会将整行拆分为多个值并将它们放入一个数组中。 然后,您可以从数组中获取每个项目并按照您的意图单独解析。

下次请避免发布屏幕截图,使用正确的格式和文本,以便有人可以轻松地将您的代码或测试数据复制到 IDE 并重现该场景。

对于Scanner ,必须使用hasNextLine, nextLine, hasNext, next, hasNextInt, nextInt等。 我会这样做:

  • 使用路径和文件 - 更新更通用的类 io 文件。
  • 文件可以读取行,这里我使用 Files.lines 给出 Stream 行,有点像循环。
  • Try-with-resources: try (AutoCloseable in =...) {... }确保始终隐式调用in.close() ,即使在异常或返回时也是如此。
  • 该行没有行尾。
  • 该行被分成由一个或多个空格分隔的单词。
  • 仅处理至少包含 6 个单词的行。
  • 从单词创建一个房间。
  • 收集一组 Room-s。

所以:

Path file = Paths.get("rooms.txt");
try (Stream<String> in = Files.lines(file)) {
    rooms = in                                  // Stream<String>
        .map(line -> line.split(" +"))          // Stream<String[]>
        .filter(words -> words.length >= 6)
        .map(words -> {
            int roomNum = Integer.parseInt(words[0]);
            String type = words[1];
            double price = Double.parseDouble(words[2]);
            boolean balcony = Boolean.parseBoolean(words[3]);
            boolean lounge = Boolean.parseBoolean(words[4]);
            String reserved = words[5];
            return new Room(roomNum, type, price, balcony, lounge, reserved);
        })                                      // Stream<Room>
        .toArray(Room[]::new);                  // Room[]
}

对于局部变量,使用前面带有小写字母的 camelCase。

代码使用系统默认的字符编码将文件中的字节转换为java Unicode String。 如果您想要所有 Unicode 符号,您可以将您的列表存储为 Unicode UTF-8,并阅读如下:

try (Stream<String> in = Files.lines(file, StandardCharsets.UTF_8)) {

另一个问题是不精确的浮点double 您可以改用BigDecimal 它具有精度:

            BigDecimal price = new BigDecimal(words[2]);

然而,它更加冗长,因此您需要查看几个示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM