提问人:Fuji 提问时间:10/6/2022 最后编辑:JonasFuji 更新时间:5/10/2023 访问量:197
如何验证 Scanner 类中的下一个令牌是否为空,以便区分循环条件?
How do I verify if the next token in a Scanner class is empty in order to differentiate between loop conditions?
问:
我正在尝试解决教授给我们的一个问题。我需要通过附加带有空格的出现和带有新行的出现来对文件进行排序。我在确定 while 循环中 else if 子句的语法时遇到问题。data.txt
;
;;
Data.txt contains the following 2 lines:
John;88;卡尔;;雅芙
·海伦;玛丽;;123;99
The current code is as follows:
import java.io.*;
import java.util.*;
class Delimit {
public static void main(String[] args) throws IOException {
// Initiates new FileInputStream to read text document
File f = new File("data.txt");
// Initiates new Scanner to parse the file, and delimit at ";"
Scanner s = new Scanner(f).useDelimiter(";");
// Parses through each token
while (s.hasNext()) {
//
if (s.hasNext()) {
// Prints next token followed by a space
System.out.print(s.next() + " ");
}
// else if (next token is empty) {
// Prints next token followed by a new line
System.out.print(s.next() + "\n");
}
}
s.close(); // Closes the Scanner
}
}
如果有更好的划界和替换方法的方法,请启发我!我一直在努力提高我对正则表达式和字符串分界线的掌握。谢谢!
答:
2赞
Scary Wombat
10/6/2022
#1
就我个人而言,我会放弃使用分隔符,而只是做一个简单的替换,->然后;;
\n
;
-> ;
Scanner s = new Scanner(f);
String line = s.nextLine ();
while (line != null) {
s.o.p (line.replace(";;", "\n").replace(";", "; "));
line = s.nextLine ();
}
评论
0赞
Fuji
10/7/2022
谢谢!这是一种更简洁的方法,尽管我选择了 @oleg.cherednik 提供的答案,因为它更适合我已经创建的代码结构。
1赞
Oleg Cherednik
10/6/2022
#2
public static void main(String... args) throws FileNotFoundException {
try (Scanner scan = new Scanner(new File("data.txt"))) {
scan.useDelimiter("[;\r]"); // \r as line separator in the file under Windows
boolean addSpace = false;
while (scan.hasNext()) {
String str = scan.next().trim();
if (str.isEmpty()) {
System.out.println();
addSpace = false;
} else {
if (addSpace)
System.out.print(' ');
addSpace = true;
System.out.print(str);
}
}
}
}
评论
;
带有空格“,它正在替换 - 分隔符不包含在s.hasNext("")
if
s.next()
isExpty()
s.nxet()
System.out.print(something + "\n");
System.out.println(something);
println
// Closes the Scanner