//不管在什么时候,都要尽可能使用熟悉的惯用法和API。 //一个 char 不是一个 String,而是更像一个 int。 //Random.nextInt(int)的规范描述道:“返回一个伪随机的、均等地分布在从0 //(包括)到指定的数值(不包括)之间的一个int 数值”[Java-API]。 //3个bug:分支2永远不会到达;没有break,总是最后的default为最后内容; //StringBuffer没有char参数构造器,new StringBuffer('M'); 调用的是设置缓冲区初始容量的int型构造器。 Random rnd = new Random(); StringBuffer word = null; switch(rnd.nextInt(2)) { case 1: word = new StringBuffer('P'); case 2: word = new StringBuffer('G'); default: word = new StringBuffer('M'); } word.append("a"); word.append('i'); word.append('n'); System.out.println(word); //输出总是ain //正确和更优雅的解决办法: System.out.println("PGM".charAt(rnd.nextInt(3)) + "ain");
//String.replaceAll 接受了一个正则表达式作为它的第一个参数,而并非接受了一个字符序列字面常量。 //正则表达式“.”可以匹配任何单个的字符,要想只匹配句点符号,在正则表达式中的句点必须在其前面添加 //一个反斜杠(\)进行转义。 System.out.println(Puzzlers.class.getName().replaceAll(".", "/") + ".class"); //输出为://///////////////////////////////////.class System.out.println(Puzzlers.class.getName().replaceAll("\\.", "/") + ".class"); //输出为:com/jaeson/javastudy/puzzler/Puzzlers.class //在替代字符串中出现的反斜杠会把紧随其后的字符进行转义,从而导致其被按字面含义而处理了。 //Exception:String index out of range try { System.out.println(Puzzlers.class.getName().replaceAll("\\.", File.separator) + ".class"); } catch (StringIndexOutOfBoundsException ex) { System.out.println("StringIndexOutOfBoundsException: " + ex.getMessage()); } //使用1.5新的replace方法:它将模式和替代物都当作字面含义的字符串处理。 System.out.println(Puzzlers.class.getName().replace(".", File.separator) + ".class");