【发布时间】:2017-05-11 12:08:02
【问题描述】:
给定下面的代码,它会输出:
Feed a chunk of data here:
I have found: 0 words; 0 ints; 0 booleans;
如果我输入 10 个空格并留下两个 useDelimiter 方法调用的注释,并输出:
Feed a chunk of data here:
I have found: 9 words; 0 ints; 0 booleans;
sssssssss
如果我键入了完全相同的 10 个空格,但确实使用了两个 useDelimiter 调用之一。 为什么会这样?不应该一样吗?这是代码,谢谢:
package com.riccardofinazzi.regex;
import java.io.Console;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.ArrayList;
class ScanNext {
public static void main(String[] args) {
/* match counters */
int hits_s = 0, hits_i = 0, hits_b = 0;
/* current token value */
String s;
Integer i;
Boolean b;
ArrayList<Object> al = new ArrayList<Object>();
Scanner s1 = new Scanner(System.console().readLine("Feed a chunk of data here: "));
/* not needed as this is def behaviour, I put it here to not forget the method */
//s1.useDelimiter(Pattern.compile("\\s"));
//s1.useDelimiter(" ");
while(s1.hasNext()) {
if ( s1.hasNextInt()) {
al.add(s1.nextInt()); hits_i++;
} else if ( s1.hasNextBoolean()) {
al.add(s1.nextBoolean()); hits_b++;
} else { al.add(s1.next()); hits_s++;
}
}
System.out.println("I have found:\t"+hits_s+" words; "+hits_i+" ints; "+hits_b+" booleans;");
for (Object in : al) {
if (in instanceof String)
System.out.print("s");
if (in instanceof Integer)
System.out.print("i");
if (in instanceof Boolean)
System.out.print("b");
}
System.out.print("\n");
}
}
【问题讨论】:
标签: java java.util.scanner delimiter