public class StrTokDemo {
public final static int MAXFIELDS=5;
public final static String DELIM="|";
public static String[] process(String line){
String[] results=new String[MAXFIELDS];
StringTokenizer st=new StringTokenizer(line,DELIM,true);
int i=0;
while(st.hasMoreTokens()){
String s=st.nextToken();
if(s.equals(DELIM)){
if(i++>=MAXFIELDS)
throw new IllegalArgumentException("Input line"+line+"has too many fields");
continue;
}
results[i]=s;
}
return results;
}
public static void printResults(String input,String[] outputs){
System.out.println("Input:"+input);
for(int i=0;i<outputs.length;i++)
System.out.println("Output"+i+"was:"+outputs[i]);
}
public static void main(String[] a){
printResults("A|B|C|D",process("A|B|C|D"));
printResults("A||C|D",process("A||C|D"));
printResults("A|||D|E",process("A|||D|E"));
}
}
------解决方案--------------------
printResults("A||C|D",process("A||C|D"));
printResults("A|||D|E",process("A|||D|E"));
这里的a 到c d中间少个b 用null代替
ade中间少2个 用null代替
------解决方案--------------------
问题在这里
if(i++>=MAXFIELDS)
throw new IllegalArgumentException("Input line"+line+"has too many fields");
continue;
它动到了i,当s==DELIM时,i照常+1,之后不往result中写入任何String对象就continue
如果没有连续的|出现,程序正常
如果连续的|出现,就会造成result[i]被跳过,保持了初始化时的值null
(其实不用这么麻烦,StringTokenizer st=new StringTokenizer(line,DELIM,true);的第3个参数去掉或改为false就可以了)