[英]Split String input from file into an array using scanner
我有一個我正在閱讀的文本文件,它看起來像這樣:
pizza, fries, eggs.
1, 2, 4.
我正在使用 Scanner 類掃描這個 .txt,我想將輸入插入到 ArrayList 中。 我知道有一種方法可以拆分字符串並使用","
作為分隔符,但我似乎無法找到如何以及在何處應用它。 注意: .
用作自己的分隔符,因此掃描器知道它需要檢查下一行並將其添加到不同的 ArrayList。
這是我從帶有 ArrayList 設置的類中的相應代碼:
public class GrocerieList {
static ArrayList<String> foodList = new ArrayList<>();
static ArrayList<String> foodAmount = new ArrayList<>();
}
這是來自掃描 .txt 輸入的類的代碼:
public static void readFile() throws FileNotFoundException {
Scanner scan = new Scanner(file);
scan.useDelimiter("/|\\.");
scan.nextLine(); // required because there is one empty line at .txt start
if(scan.hasNext()) {
GrocerieList.foodList.add(scan.next());
scan.nextLine();
}
if(scan.hasNext()) {
GrocerieList.foodAmount.add(scan.next());
scan.nextLine();
}
}
我在哪里可以拆分字符串? 如何? 也許我的方法有缺陷,我需要改變它? 非常感謝任何幫助,謝謝!
使用nextLine()
從文件中讀取一行,然后消除結束句點,並以逗號分隔。
並使用try-with-resources正確關閉文件。
public static void readFile() throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
scan.nextLine(); // required because there is one empty line at .txt start
GrocerieList.foodList.addAll(Arrays.asList(scan.nextLine().replaceFirst("\\.$", "").split(",\\s*")));
GrocerieList.foodAmount.addAll(Arrays.asList(scan.nextLine().replaceFirst("\\.$", "").split(",\\s*")));
}
}
通常你會保存從nextLine
方法中讀出的nextLine
,並使用split
方法將列表分解成一個數組,然后將它存儲到你的目標中。 如果需要轉換,例如從字符串到整數,請單獨進行。
String lineContent = scan.nextLine();
String[] components = lineContent.split(","); //now your array has "pizza", "fries", "eggs" etc.
最簡單的方法是使用 String#split。 你也不想要'next',而是nextLine
GrocerieList.foodList.addAll(Arrays.asList(scan.nextLine().replaceFirst("\\\\.$", "").split(", ")));
(應該工作,但沒有測試它)。
有關掃描儀類的更多信息,請參閱https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.