首页 > 解决方案 > 读取数据并存储在数组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();

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

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

在此处输入图像描述

标签: javaarrays

解决方案


像这样改变你的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
}

推荐阅读