java nextint是什麼,讓我們一起了解一下?
nextint是java.util.Random類產生的隨機數,即給定一個參數n,nextInt(n)將返回一個大於等於0小於n的隨機數,即:0 <= nextInt(n) < n。
nextint函數是怎樣實現的?
具體代碼如下:
/** * Returns a pseudo-random uniformly distributed {@code int} * in the half-open range [0, n). */ public int nextInt(int n) { if (n > 31); } int bits, val; do { bits = next(31); val = bits % n; } while (bits - val + (n - 1) < 0); return val; }
next類似於nextInt(只能輸入整數)、nextDouble(只能輸入雙精度浮點數),可以輸入任意類型的值。
首先,next()一定要讀取到有效字元后纔可以結束輸入,對輸入有效字元之前遇到的空格鍵、Tab鍵或Enter鍵等結束符,next()方法會自動將其去掉,只有在輸入有效字元之後,next()方法纔將其後輸入的空格鍵、Tab鍵或Enter鍵等視爲分隔符或結束符。
簡單地說,next()查找並返回來自此掃描器的下一個完整標記。完整標記的前後是與分隔模式匹配的輸入資訊,所以next方法不能得到帶空格的字元串而nextLine()方法的結束符只是Enter鍵,即nextLine()方法返回的是Enter鍵之前的所有字元,它是可以得到帶空格的字元串的。