日期:2014-05-20  浏览次数:20845 次

考题求助 正则
这个题目的答案怎么解释啊

Java code

import java.io.*;
import java.util.*;
import java.util.regex.*;

public class SCJP {
    
    public static void main(String args[]){
        String input ="10 apples 20 oranges 33 pears";
        Scanner s=new Scanner(input).useDelimiter("\\d*");
        System.out.print(s.toString());
        String str[]=new String[6];
        int i=0;
        while(s.hasNext()){
            str[i]=s.next();
            System.out.println(str[i++]);
        }
        s.close();
    }
}


答案:
a
p
p
l
e
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at SCJP.main(SCJP.java:14)

------解决方案--------------------
问题的关键在("\\d*")这里,改为("\\d+")就可以分离出字符串了,什么原因自己看API吧

------解决方案--------------------
Java code

public static void main(String args[]) {
         String input = "10 apples 20 oranges 33 pears";
        Scanner s = new Scanner(input).useDelimiter("\\d+");
        System.out.println(s.toString());
        String str[] = new String[6];
        int i = 0;
        while (s.hasNext()) {
            str[i] = s.next();
            System.out.println(str[i++]);
        }
        s.close();
        s.close();
    }