[英]How to read the data stored in a text file into an array, then sort that data and store it
[英]How to read a text file with multiple data types and store them in an Array?
我正在嘗試讀取各種數據的文本文件並將其存儲到數組中,以便在接收到用戶輸入后我可以比較它以查看數組內是否有任何匹配項。
示例文本:
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;
}
這是正確的方法還是我應該嘗試其他方法?
任何見解或建議將不勝感激。 謝謝。
您閱讀和解析很好,但是您沒有保存任何內容,您一直用最后一個info
覆蓋result
,因此您的方法僅返回一個Seats
實例,最后一個,使用List
輕松添加您創建的所有 Seats
經過一些改進
try_with-resources
用於自動關閉掃描儀
一排是一個座位,命名為class Seat
static List<Seat> read() {
List<Seat> results = new ArrayList<>();
File read = new File("seats.txt");
String dataRead;
try (BufferedReader reader = new BufferedReader(new FileReader(read))) {
while ((dataRead = reader.readLine()) != null) {
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];
Seat info = new Seat(seatID, seatClass, window, aisle, table, seatPrice, seatFree);
System.out.println(info);
results.add(info);
}
} catch (FileNotFoundException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return results;
}
使用 Jackson。 https://cowtowncoder.medium.com/reading-csv-with-jackson-c4e74a15ddc1 。 見倒數第二個例子。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.