Java Random nextBytes() 方法



描述

nextBytes(byte[] bytes) 方法用於生成隨機位元組並將它們放入使用者提供的位元組陣列中。

宣告

以下是 java.util.Random.nextBytes() 方法的宣告。

public void nextBytes(byte[] bytes)

引數

  • bytes - 這是用於存放隨機位元組的非空位元組陣列。

返回值

異常

獲取隨機位元組陣列示例

以下示例演示了 Java Random nextBytes() 方法的使用。首先,我們建立了一個 Random 物件,然後使用 nextBytes() 獲取隨機位元組陣列並列印它。

package com.tutorialspoint;

import java.util.Random;

public class RandomDemo {
   public static void main( String args[] ) {
      
      // create random object
      Random randomNo = new Random();

      // create byte array
      byte[] nbyte = new byte[30];

      // put the next byte in the array
      randomNo.nextBytes(nbyte);

      // check the value of array   
      System.out.println("Value of byte array: ");
      
      for (int i = 0; i < nbyte.length; i++) {
         System.out.print(" " + nbyte[i] );
      }
   }      
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果。

Value of byte array: 
 74 -7 25 110 -56 -112 -95 -56 28 27 -59 -52 -64 2 -73 123 100 22 -42 -51 79 -63 -53 4 53 -78 -54 25 -51 -15

使用給定種子獲取隨機位元組陣列示例

以下示例演示了 Java Random nextBytes() 方法的使用。首先,我們使用種子值建立了一個 Random 物件,然後使用 nextBytes() 獲取隨機位元組陣列並列印它。

package com.tutorialspoint;

import java.util.Random;

public class RandomDemo {
   public static void main( String args[] ) {
      
      // create random object
      Random randomNo = new Random();

      // create byte array
      byte[] nbyte = new byte[30];

      // put the next byte in the array
      randomNo.nextBytes(nbyte);

      // check the value of array   
      System.out.println("Value of byte array: ");
      
      for (int i = 0; i < nbyte.length; i++) {
         System.out.print(" " + nbyte[i] );
      }
   }      
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果。

Value of byte array: 
 97 -11 79 -8 -120 109 -34 -111 113 -84 27 96 -127 118 -115 103 -73 83 110 -82 36 77 36 -72 -22 89 23 83 -111 -93
java_util_random.htm
廣告