Puzzle 19: Classy Fire
以下代码片段输出什么?
public class Classifier {
public static void main(String[] args) {
System.out.println(classfiy('n') + classfiy('+') + classfiy('2'));
}
static String classfiy(char ch) {
if ("0123456789".indexOf(ch) >= 0)
return "NUMERAL ";
if ("abcdefghijklmnopqrstuvwxyz".indexOf(ch) >= 0)
return "LETTER ";
/*
if ("+-*/".indexOf(ch) >= 0)
return "OPERATOR";
*/
return "UNKNOWN";
}
}
如果你仔细看, 并得出结果为:"LETTER UNKNOWN NUMERAL ", 那就中套了, 这里要说明的问题并非要讨论 String.indexOf(int) 方法, 而是注释, 真是出人意料. 注意第三个 if 块的注释部分, 高亮背景为黄色的, 先就匹配了, 高亮为绿色的 */因为没有匹配的/*, 程序就报错了.
教训: 用双斜杠的注释比较保险.
另外: /* */ 格式的注释是不能嵌套的.
参考
- Java API document: String.indexOf(int ch)
- JLS 3.7 Comments
- JLS 14.20, 条件编译技术,待翻译。TODO
- 代码: http://bit.ly/f4yAg