gpt4 book ai didi

java - 用三个单词分割字符串

转载 作者:行者123 更新时间:2023-12-01 13:18:59 25 4
gpt4 key购买 nike

分割包含三个单词的字符串的最佳方法是什么?

我的代码现在看起来像这样(请参阅下面的更新代码):

BufferedReader infile = new BufferedReader(new FileReader("file.txt"));

String line;
int i = 0;

while ((line = infile.readLine()) != null) {
String first, second, last;
//Split line into first, second and last (word)

//Do something with words (no help needed)
i++;
}

这是完整的 file.txt:

Allegrettho     Albert          0111-27543
Brio Britta 0113-45771
Cresendo Crister 0111-27440
Dacapo Dan 0111-90519
Dolce Dolly 0116-31418
Espressivo Eskil 0116-19042
Fortissimo Folke 0118-37547
Galanto Gunnel 0112-61805
Glissando Gloria 0112-43918
Grazioso Grace 0112-43509
Hysterico Hilding 0119-71296
Interludio Inga 0116-22709
Jubilato Johan 0111-47678
Kverulando Kajsa 0119-34995
Legato Lasse 0116-26995
Majestoso Maja 0116-80308
Marcato Maria 0113-25788
Molto Maja 0117-91490
Nontroppo Maistro 0119-12663
Obligato Osvald 0112-75541
Parlando Palle 0112-84460
Piano Pia 0111-10729
Portato Putte 0112-61412
Presto Pelle 0113-54895
Ritardando Rita 0117-20295
Staccato Stina 0112-12107
Subito Sune 0111-37574
Tempo Kalle 0114-95968
Unisono Uno 0113-16714
Virtuoso Vilhelm 0114-10931
Xelerando Axel 0113-89124

@Pshemo 建议的新代码:

public String load() {
try {
Scanner scanner = new Scanner(new File("reg.txt"));

while (scanner.hasNextLine()) {
String firstname = scanner.next();
String lastname = scanner.next();
String number = scanner.next();
list.add(new Entry(firstname, lastname, number));
}
msg = "The file reg.txt has been opened";
return msg;
} catch (NumberFormatException ne) {
msg = ("Can't find reg.txt");
return msg;
} catch (IOException ie) {
msg = ("Can't find reg.txt");
return msg;
}
}

我收到多个错误,出了什么问题?

最佳答案

假设每行始终包含三个单词而不是拆分,您只需对每行使用 Scanner 方法 next 三次即可。

Scanner scanner = new Scanner(new File("file.txt"));
int i = 0;
while (scanner.hasNextLine()) {
String first = scanner.next();
String second = scanner.next();
String last = scanner.next();
//System.out.println(first+": "+second+": "+last);
i++;
}

关于java - 用三个单词分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22203954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com