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.