当数字以任意数量的换行符分隔时,如何使用java.util.Scanner
类读取输入(数字)?
示例可能如下所示:
23333
.
.
.
332332
.
.
.
3333
答案 0 :(得分:1)
您可以设置多行delimeter。假设您从文件中读取了数字:
Scanner scanner = new Scanner(new File("test.txt"));
scanner.useDelimiter("[\r\n]+"); // for unix "\n" and windows "\r\n" endings
while (scanner.hasNextInt()) {
int x = scanner.nextInt();
System.out.println("read number = " + x);
}
scanner.close();