假如你希望產(chǎn)生0到某個上界的隨機數(shù)。許多人會這么寫 Random rnd = new Random(); public int random(int n){ return Math.abs(rnd.nextInt()) % n; } 請注重,這是錯誤的,或者至少是不嚴謹?shù)摹?br /> 這么寫有個錯誤。有可能得到指定范圍以外的數(shù),當nextInt()返回Integer.MIN_VALUE時, abs(nextInt())也返回Integer.MIN_VALUE,然后假如n不是2的乘方,呵呵,負數(shù)出現(xiàn)了。 建議使用Random.nextInt(int)這個方法,這是經(jīng)過修正的。