java Random.nextInt()方法的具體使用
lic int nextInt(int n)
該方法的作用是生成一個隨機的int值,該值介于[0,n)的區間,也就是0到n之間的隨機int值,包含0而不包含n。
直接上代碼:
package org.xiaowu.random.demo;import java.util.Random;import org.junit.Test;public class RandomDemo { @Test public void Demo(){ Random rnd = new Random(); int code = rnd.nextInt(8999) + 1000; System.out.println('code:'+code); } @Test public void Demo1(){ Random r = new Random(); int nextInt = r.nextInt(); Random r1 = new Random(10); int nextInt2 = r1.nextInt(); System.out.println('nextInt:'+nextInt); System.out.println('nextInt2:'+nextInt2); } /** * 生成[0,1.0)區間的小數 * */ @Test public void Demo2(){ Random r = new Random(); double d1 = r.nextDouble(); System.out.println('d1:'+d1); } /** * 生成[0,5.0)區間的小數 * */ @Test public void Demo3(){ Random r = new Random(); double d2 = r.nextDouble()* 5; System.out.println('d1:'+d2); } /** * 生成[1,2.5)區間的小數 * */ @Test public void Demo4(){ Random r = new Random(); double d3 = r.nextDouble() * 1.5 + 1; System.out.println('d1:'+d3); } /** * 生成任意整數 * */ @Test public void Demo5(){ Random r = new Random(); int n1 = r.nextInt(); System.out.println('d1:'+n1); } /** * 生成[0,10)區間的整數 * */ @Test public void Demo6(){ Random r = new Random(); int n2 = r.nextInt(10); int n3 = Math.abs(r.nextInt() % 10); System.out.println('n2:'+n2); System.out.println('n3:'+n3); } /** * 生成[0,10]區間的整數 * */ @Test public void Demo7(){ Random r = new Random(); int n3 = r.nextInt(11); int n4 = Math.abs(r.nextInt() % 11); System.out.println('n3:'+n3); System.out.println('n4:'+n4); } /** * 生成[-3,15)區間的整數 * */ @Test public void Demo8(){ Random r = new Random(); int n4 = r.nextInt(18) - 3; int n5 = Math.abs(r.nextInt() % 18) - 3; System.out.println('n4:'+n4); System.out.println('n5:'+n5); } }
Java中使用Random類中的nextInt()方法返回一個偽隨機數
問題
今天想讓程序返回一個區間內的隨機數。忘記怎么寫了,就去百度搜給出的結果并不對。
import java.util.Random; /** * @author HP * @date 2019/4/16 */public class randomTest { public static void main(String[] args) { Random random = new Random(); //生成64-128內的隨機數 int i = random.nextInt() * (128 - 64 + 1) + 64; /** * 生成 [m,n] 的數字 * int i1 = random.nextInt() * (n-m+1)+m; * */ //生成0-64內的數字 int i1 = random.nextInt() * (64-0+1); /** * 生成0-n之內的數字 * int i1 = random.nextInt() * (n-0+1); * * * */ }}
這樣是不對的,我就去查看API文檔,發現nextInt()可以有參數也可以無參數。
無參數的方法直接調用返回的是一個很大的正負區間上的數。
如果想返回想要的范圍內的數,應該:
package chapter6;import java.util.Random;import org.omg.Messaging.SyncScopeHelper;public class RandomTest { public static void main(String[] args) { Random random = new Random(); for(int i=0;i<200;i++) {// 輸出為0~13之間的整數 System.out.println(random.nextInt(14)); } System.out.println('----------------------------'); for(int j=0;j<100;j++){// 輸出為-9~0之間的整數 System.out.println(random.nextInt(10)-9); } } }
到此這篇關于java Random.nextInt()方法的具體使用的文章就介紹到這了,更多相關java Random.nextInt使用內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
