[英]problem with use delimiter in scanner class
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
錯誤。 什么是問題?
您必須在useDelimiter
方法中使用正確的正則表達式。 以下代碼應該可以工作:
try {
Scanner in = new Scanner(new File("text.txt"));
Formatter out = new Formatter("text1.txt");
in.useDelimiter(",|\n|\r\n|\\s+");
int num = in.nextInt();
for(int i = 0; i < num && in.hasNext(); i++)
out.format("string # %d is: [%s]\n", i, in.next() );
out.close();
}
catch (Exception e) {
System.err.print("Exception: " + e);
}
對於給定的輸入
4
hello,my,name,is
它輸出:
string # 0 is: [hello]
string # 1 is: [my]
string # 2 is: [name]
string # 3 is: [is]
問題是當您指定分隔符是逗號時,換行符不再是分隔符。
將您的文件更改為 4,hello,my,name,is 並且它應該可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.