我有一个文本文件(statecapitals.txt),其中包含“State - Capital”:
Alaska - Juneau
Arizona - Phoenix
Arkansas - Little Rock
California - Sacramento
Colorado - Denver
Connecticut - Hartford
Delaware - Dover
Florida - Tallahassee
如何将第一个字段放入arraylist中,将第二个字段放入另一个arraylist中(我无法修改文本文件)?
答案 0 :(得分:2)
您可以使用.split(" - ")
拆分行。
请参阅JavaDoc。
例如:
String content = "Alaska - Juneau\n" +
"Arizona - Phoenix\n" +
"Arkansas - Little Rock\n" +
"California - Sacramento\n" +
"Colorado - Denver\n" +
"Connecticut - Hartford\n" +
"Delaware - Dover\n" +
"Florida - Tallahassee\n";
Scanner scanner = new Scanner(content);
List<String> states = new ArrayList<>();
List<String> capitals = new ArrayList<>();
while (scanner.hasNextLine()) {
String[] parts = scanner.nextLine().split(" - ");
states.add(parts[0]);
capitals.add(parts[1]);
}
System.out.println(states);
System.out.println(capitals);
答案 1 :(得分:0)
假设您已设法迭代文件的每一行,并在String
中将每一行添加为List<String> lines
;
您现在可以为每个字符串创建2个新List
,如下所示:
List<String> states = new ArrayList<>();
List<String> capitals = new ArrayList<>();
for (String line : lines) {
String[] words = line.split(" - ");
if (words.length == 2) {
states.add(words[0]);
capitals.add(words[1]);
}
}