翻译人员: 铁锚
翻译日期: 2013年11月20日
原文链接: A Puzzle from “A Brief History of the (Java) World and a Peek Forward” Presented by Neal Gafter
以下是来自Neal Gafter 演讲中的一个Java谜题:
- import java.util.Random;
-
- public class Rhymes {
- private static Random rnd = new Random();
-
-
-
-
-
-
-
- public static void main(String[] args) {
- 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);
- }
- }
正确答案是哪一个呢?
正确答案是 D.
该程序中有三处缺陷:
1. 显然,在 switch语句中没有 break
2. nextInt(2) 返回的结果只有 0 或者 1
3. ‘P’, ‘G’, ‘M’ 是char型手, 而不是String对象,所以被自动转换为int型,调用了不符合预期的构造函数.
如果想要了解更多,请参考布洛克(Joshua Bloch)与 加夫特(Neal Gafter)的图书, 《Java解惑》
相关阅读:
- 十大常见Java String问题
- Declaration, Initialization and Scoping for Java
- Java Code: Given range, return an array of N random numbers
- Constructor Can Throw Exceptions in Java!