本帖最后由 徐晓磊 于 2012-4-22 04:24 编辑
- import java.util.regex.*;
- import java.util.*;
- public class AutoSelectString { //http://bbs.itheima.com/thread-12655-1-1.html的题目
-
- private String poems;
- private Vector<String> poemsPart;// 存放每一句
- private Vector<Integer> poemsNumber;//存放随即产生的每一句空白处的索引
-
- public AutoSelectString(String poems){
- this.poems = poems;
- poemsPart = new Vector<String>();
- poemsNumber = new Vector<Integer>();
- autoMaker();
- show();
- }
-
- //使用正则表达式
- public void autoMaker(){
- Pattern pattern = Pattern.compile("\\S*\\s");
- Matcher matcher = pattern.matcher(poems);
- while(matcher.find()){
- poemsPart.add(matcher.group());
- }
- for(int i=0;i<poemsPart.size();i++){
- String str = poemsPart.get(i);
- int random = new Random().nextInt(str.length()-2);
- poemsNumber.add(random);
- }
-
- }
- //输出
- public void show(){
- char[] chars = new char[poemsPart.size()];
- for(int i=0;i<chars.length;i++){
- chars[i] = poemsPart.get(i).charAt(poemsNumber.get(i));
- System.out.print(poemsPart.get(i).replace(chars[i],'_'));
- }
- System.out.println("");
- //下面的输出没有做到能够对于任意的诗句进行选项排列组合输出,只能只对于诗句是四言的,可以通过添加排列组合算法实现模块化输出四言,八言,词等
- System.out.println("A : "+chars[0] + " " +chars[1]+ " " +chars[2]+ " " +chars[3]);
- System.out.println("B : "+chars[1] + " " +chars[3]+ " " +chars[2]+ " " +chars[0]);
- System.out.println("C : "+chars[2] + " " +chars[1]+ " " +chars[0]+ " " +chars[1]);
- System.out.println("D : "+chars[3] + " " +chars[2]+ " " +chars[1]+ " " +chars[0]);
- }
-
-
- public static void main(String[] args){
- //诗句格式是每一句结尾加一个空格
- new AutoSelectString("床前明月光, 疑是地上霜, 举头望明月, 低头思故乡。 ");
-
- }
- }
复制代码 以下是运行截图
|
|