翻譯人員: 鐵錨
翻譯日期: 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;// Rhymes,押韻public class Rhymes { private static Random rnd = new Random(); /** * 以下程式的輸出有可能是什麼? * (a) Pain ,Gain 或者 Main (根據各個隨機數) * (b) Pain 或者 Main (根據隨機數) * (c) Main (總是這個) * (d) 以上都不對 */ 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!