Java 程式生成隨機字串


在本文中,我們將瞭解如何建立隨機字串。字串是一種包含一個或多個字元的的資料型別,並用雙引號(“ ”)引起來。

下面是相同的演示 −

假設我們的輸入是

The size of the string is defined as: 10

期望的輸出是

Random string: ink1n1dodv

演算法

Step 1 - START
Step 2 - Declare an integer namely string_size, a string namely alpha_numeric and an object of StringBuilder namely string_builder.
Step 3 - Define the values.
Step 4 - Iterate for 10 times usinf a for-loop, generate a random value using the function Math.random() and append the value using append() function.
Step 5 - Display the result
Step 6 - Stop

示例 1

在這裡,我們將所有操作繫結在“main”函式下。

public class RandomString {
   public static void main(String[] args) {
      int string_size = 10;
      System.out.println("The size of the string is defined as: " +string_size);
      String alpha_numeric = "0123456789" + "abcdefghijklmnopqrstuvxyz";
      StringBuilder string_builder = new StringBuilder(string_size);
      for (int i = 0; i < string_size; i++) {
         int index = (int)(alpha_numeric.length() * Math.random());
         string_builder.append(alpha_numeric.charAt(index));
      }
      String result = string_builder.toString();
      System.out.println("The random string generated is: " +result);
   }
}

輸出

The size of the string is defined as: 10
The random string generated is:
ink1n1dodv

示例 2

在這裡,我們將操作封裝到函式中,表現出面向物件程式設計。

public class RandomString {
   static String getAlphaNumericString(int string_size) {
      String alpha_numeric = "0123456789" + "abcdefghijklmnopqrstuvxyz";
      StringBuilder string_builder = new StringBuilder(string_size);
      for (int i = 0; i < string_size; i++) {
         int index = (int)(alpha_numeric.length() * Math.random());
         string_builder.append(alpha_numeric.charAt(index));
      }
      return string_builder.toString();
   }
   public static void main(String[] args) {
      int string_size = 10;
      System.out.println("The size of the string is defined as: " +string_size);
      System.out.println("The random string generated is: ");
      System.out.println(RandomString.getAlphaNumericString(string_size));
   }
}

輸出

The size of the string is defined as: 10
The random string generated is:
ink1n1dodv

更新於: 29-Mar-2022

633 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.