扫描仪类中使用分隔符的问题
try {
Scanner in = new Scanner(new File("text.txt"));
Formatter out = new Formatter("text1.txt");
in.useDelimiter(",");
int num = in.nextInt();//this line throws null exception
for(int i = 0; i < num && in.hasNext(); i++)
{
out.format("%s","#string \n" + i );
out.format("%s", in.next());
}
out.close();
}
catch (Exception e) {
System.out.print(e.getMessage());
}
输入是:
4
hello,my,name,is
4 是单词数。 输出必须是:
hello my name is
但它会引发 null
错误。 有什么问题吗?
try {
Scanner in = new Scanner(new File("text.txt"));
Formatter out = new Formatter("text1.txt");
in.useDelimiter(",");
int num = in.nextInt();//this line throws null exception
for(int i = 0; i < num && in.hasNext(); i++)
{
out.format("%s","#string \n" + i );
out.format("%s", in.next());
}
out.close();
}
catch (Exception e) {
System.out.print(e.getMessage());
}
the input is:
4
hello,my,name,is
4 is number of words.
the out put must be:
hello my name is
but it trow exeption with null
error.
what is problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须在
useDelimiter
方法中使用正确的正则表达式。以下代码应该可以工作:输出
对于给定的输入,
它输出:
You have to use a proper regular expression in the
useDelimiter
method. The following code should work:Output
For the given input
it outputs:
问题是,当您指定分隔符是逗号时,换行符不再是分隔符。
将文件更改为 4,hello,my,name,is 并且它应该可以工作。
The problem is that as you specify that the delimiter is a comma, the newline character is not a delimiter any more.
Change your file to 4,hello,my,name,is and it should work.