Java Random nextInt()方法与示例
隨機類nextInt()方法 (Random Class nextInt() method)
Syntax:
句法:
public int nextInt();public int nextInt(int num);nextInt() method is available in java.util package.
nextInt()方法在java.util包中可用。
nextInt() method is used to return the next pseudo-random value from this Random Value Generator.
nextInt()方法用于從此隨機值生成器返回下一個偽隨機值。
nextInt(int num) method is used to return the next pseudo-random distribute integer value between 0 and the given parameter (num) from this Random Generator.
nextInt(int num)方法用于從此隨機數生成器返回下一個介于0和給定參數(num)之間的下一個偽隨機分布整數值。
These methods may throw an exception at the time of returning the next integer value.
這些方法在返回下一個整數值時可能會引發異常。
IllegalArgumentException: This exception may throw when the given parameter (num<0) is invalid.
IllegalArgumentException :當給定參數(num <0)無效時,可能引發此異常。
These are non-static methods and it is accessible with the class object and if we try to access these methods with the class name then also we will get any error.
這些是非靜態方法,可通過類對象進行訪問,如果嘗試使用類名訪問這些方法,則也會遇到任何錯誤。
Parameter(s):
參數:
In the first case, nextInt()
在第一種情況下, nextInt()
- It does not accept any parameter.
In the second case, nextInt(int num)
在第二種情況下, nextInt(int num)
- int num – represents the last endpoint of this Random Value Generator.
- int num –表示此隨機值生成器的最后一個端點。
Return value:
返回值:
In both the cases, the return type of the method is int – it returns next pseudorandom distributed value between 0 and num.
在這兩種情況下,方法的返回類型均為int –它返回0至num之間的下一個偽隨機分布值。
Example:
例:
// Java program to demonstrate the example // of nextInt() method of Randomimport java.util.*;public class NextIntOfRandom {public static void main(String args[]) {// Instantiates Random objectRandom ran = new Random();// By using nextInt() method is// to return next int pseudo-random// value by using Random Value Generatorint val = ran.nextInt();// Display valSystem.out.println("ran.nextInt(): " + val);// By using nextInt(int) method is// to return next int pseudo-random// value between 0 and the given value// and 0 is inclusive whereas the given value // is exclusive by using Random Value Generatorval = ran.nextInt(50);// Display valSystem.out.println("ran.nextInt(50): " + val);} }Output
輸出量
RUN 1: ran.nextInt(): -1450643138 ran.nextInt(50): 13RUN 2: ran.nextInt(): 1448295644 ran.nextInt(50): 47RUN 3: ran.nextInt(): 397396236 ran.nextInt(50): 11翻譯自: https://www.includehelp.com/java/random-nextint-method-with-example.aspx
總結
以上是生活随笔為你收集整理的Java Random nextInt()方法与示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 散点图 分类_Python
- 下一篇: Python | 如何创建模块(模块示例