读取数据并存储在Java数组中
我正在写一个程序,允许用户在酒店预订房间(大学项目)。我遇到了这样一个问题:当我尝试从文件中读取数据并将其存储在数组中时,我收到一个NumberFormatException 我已经在这个问题上纠结了一段时间,不知道我哪里出了问题。我已经读过了,很明显,当我尝试将字符串转换为数字时,它会出现,但我不知道如何修复它 有什么建议吗 这是我为我的读者编写的代码。读取数据并存储在Java数组中,java,arrays,Java,Arrays,我正在写一个程序,允许用户在酒店预订房间(大学项目)。我遇到了这样一个问题:当我尝试从文件中读取数据并将其存储在数组中时,我收到一个NumberFormatException 我已经在这个问题上纠结了一段时间,不知道我哪里出了问题。我已经读过了,很明显,当我尝试将字符串转换为数字时,它会出现,但我不知道如何修复它 有什么建议吗 这是我为我的读者编写的代码。 FileReader file = new FileReader("rooms.txt"); Scanner read
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();
这是错误消息
这是我试图读取的文件中的数据:
使用
next()
而不是nextLine()
您试图将整行解析为整数。你可以把整行读成一个字符串,调用
.拆分(“”)
在上面。这将把整行分割成多个值,并将它们放入一个数组中。然后,您可以从数组中抓取每个项,并根据需要分别进行解析
请避免下次发布屏幕截图,请使用正确的格式和文本,以便有人可以轻松地将您的代码或测试数据复制到IDE并重现场景。像这样更改您的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
}
使用
Scanner
时,必须使用hasNextLine、nextLine、hasNext、next、hasNextInt、nextInt等。我会这样做:
try (Stream<String> in = Files.lines(file, StandardCharsets.UTF_8)) {
- 使用路径和文件-更新的更通用的类i.o.文件
- 文件可以读取行,这里我使用Files.lines,它提供了一个行流,有点像一个循环
- 使用资源进行尝试:
Try(AutoCloseable in=…){…}
确保始终隐式调用in.close()
,即使在异常或返回时也是如此
- 这一行没有结尾
- 该行被拆分为由一个或多个空格分隔的单词
- 仅处理至少包含6个单词的行
- 根据单词创建一个房间
- 收集一组房间-s
因此:
不过,它要详细得多,所以您需要看几个示例
try (Stream<String> in = Files.lines(file, StandardCharsets.UTF_8)) {
BigDecimal price = new BigDecimal(words[2]);