【发布时间】:2022-01-16 09:01:23
【问题描述】:
我正在尝试读取一个包含各种数据的文本文件并将其存储到一个数组中,以便在接收到用户输入后我可以比较它以查看数组内是否有任何匹配项。
示例文本:
1A 1st true false false 28.50 free
2B 2nd false true false 25.00 free
3C 3rd true true false 32.50 free
如您所见,我正在处理字符串、布尔值和双精度值。
我最初尝试读取文件并将每一行作为字符串存储在字符串数组中,但是当我需要比较用户输入时,这不起作用。
然后我尝试创建一个数组和一个子数组,如下所示:
try {
File read = new File("seats.txt");
Scanner reader = new Scanner(read);
while (reader.hasNextLine()) {
String dataRead = reader.nextLine();
String[] seatData = dataRead.split(" ");
String seatID = seatData[0];
String seatClass = seatData[1];
boolean window = Boolean.parseBoolean(seatData[2]);
boolean aisle = Boolean.parseBoolean(seatData[3]);
boolean table = Boolean.parseBoolean(seatData[4]);
double seatPrice = Double.parseDouble(seatData[5]);
String seatFree = seatData[6];
Seats info = new Seats(seatID, seatClass, window, aisle, table, seatPrice, seatFree);
result = info;
System.out.println(result); }
reader.close();
}catch (FileNotFoundException e) {
System.out.println("An error has occurred.");
e.printStackTrace(); }
return result;
}
这是正确的方法还是我应该尝试其他方法?
任何见解或建议将不胜感激。谢谢。
【问题讨论】:
-
这很好,但您没有存储您阅读的内容?你只需打印它
-
result类型是什么? -
我知道这有点超出范围,但为什么不使用 CSV 呢?