字母数字随机数序列 [5位数或6位数或任意位数] 生成

huangapple go评论79阅读模式
英文:

Alpha Numeric Random Number Sequence [5-digit or 6-digit or any digit] generation

问题

我正在尝试生成一个由字母和数字组成的5位随机数。我既使用了流(Streams),也尝试了不使用流的方式。

**代码**

    public class AlphaRandom {
        
        private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        static final Random random = new Random();
        
        
        public static void main(String args[]) {
            int length = 5;
            String seq = randomAlphaNumeric(length);        
            System.out.println("随机数(普通):" + seq);        
            IntStream.range(0,1).forEach(i->System.out.println("随机数(流):" + generateRandomString(random, length)));
            
        }
        
        // 使用流
        private static String generateRandomString(Random random, int length){
            return random.ints(48,122)
                    .filter(i-> (i<57 || i>65) && (i <90 || i>97))
                    .mapToObj(i -> (char) i)
                    .limit(length)
                    .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
                    .toString();
        }
        
        // 普通方法
        public static String randomAlphaNumeric(int count) {
    
            StringBuilder builder = new StringBuilder();    
            while (count-- != 0) {    
                int character = (int)(Math.random()*ALPHA_NUMERIC_STRING.length());    
                builder.append(ALPHA_NUMERIC_STRING.charAt(character));    
            }    
            return builder.toString();
        }
    }

**示例输出**:

    随机数(普通):VYAXC
    随机数(流):LdBN6
    
    随机数(普通):2ANTT
    随机数(流):hfegc
    
    随机数(普通):JWK4Y
    随机数(流):8mQXK

但是我无法始终生成以“大写字母”开头的序列。有人可以帮帮我吗?
英文:

Hi I am trying to generate a 5 digit random number which is alpha numeric in nature. I am doing both with without using Streams.

CODE

public class AlphaRandom {
	
	private static final String ALPHA_NUMERIC_STRING = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789&quot;;
	static final Random random = new Random();
	
	
	public static void main(String args[]) {
		int length = 5;
		String seq = randomAlphaNumeric(length);		
		System.out.println(&quot;Random Number Normal  : &quot; +seq);		
        IntStream.range(0,1).forEach(i-&gt;System.out.println(&quot;Random Number Streams : &quot; +generateRandomString(random, length)));
		
	}
	
	// Using Streams
	private static String generateRandomString(Random random, int length){
        return random.ints(48,122)
                .filter(i-&gt; (i&lt;57 || i&gt;65) &amp;&amp; (i &lt;90 || i&gt;97))
                .mapToObj(i -&gt; (char) i)
                .limit(length)
                .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
                .toString();
    }
	
    // Normal 
	public static String randomAlphaNumeric(int count) {

		StringBuilder builder = new StringBuilder();	
		while (count-- != 0) {	
			int character = (int)(Math.random()*ALPHA_NUMERIC_STRING.length());	
			builder.append(ALPHA_NUMERIC_STRING.charAt(character));	
		}	
		return builder.toString();
	}
}

Sample Outputs :

Random Number Normal  : VYAXC
Random Number Streams : LdBN6

Random Number Normal  : 2ANTT
Random Number Streams : hfegc

Random Number Normal  : JWK4Y
Random Number Streams : 8mQXK

But I am unable to generate the sequence always starting with a UpperCase only.
Can someone help me out.

答案1

得分: 1

我将使用来自Apache库的RandomStringUtils来执行此操作。这样做的原因是减少代码量,我认为这样代码的可读性更好。

这是可以执行所需操作的我的代码

import org.apache.commons.lang3.RandomStringUtils;

public class GenerateRandomString {
    public static void main(String[] args) {
        int keyLength = 5; // 根据要求允许的字符数
        String randomAlphanumeric = RandomStringUtils.randomAlphanumeric(keyLength);
        System.out.println("randomAlphanumeric generated is " + randomAlphanumeric);
        String upperCaseRandom = randomAlphanumeric.substring(0, 1).toUpperCase() + randomAlphanumeric.substring(1);
        System.out.println("upperCaseRandom generated is " + upperCaseRandom);
    }
}

它会生成以下输出:

randomAlphanumeric generated is m8OiR
upperCaseRandom generated is M8OiR
我使用`substring`方法将第一个字符变为大写,根据问题的要求。
英文:

I will use RandomStringUtils from the apache library to do this. The reason to do this is less code and I believe better readability of the code.

This is my code which can do the required thing

import org.apache.commons.lang3.RandomStringUtils;

public class GenerateRandomString {
    public static void main(String[] args) {
        int keyLength = 5; // Number of character allowed as per requirement
        String randomAlphanumeric = RandomStringUtils.randomAlphanumeric(keyLength);
        System.out.println(&quot;randomAlphanumeric generated is &quot; + randomAlphanumeric);
        String upperCaseRandom = randomAlphanumeric.substring(0, 1).toUpperCase() + randomAlphanumeric.substring(1);
        System.out.println(&quot;upperCaseRandom generated is &quot; + upperCaseRandom);
    }
}

It would generate the following output:

randomAlphanumeric generated is m8OiR
upperCaseRandom generated is M8OiR

I am making the first character to uppercase as required by question using the substring method.

答案2

得分: 1

最简单的方法是,在返回字符串之前(生成字符串后),您可以取第一个字母,然后应用 toUpperCase,对剩余的字符应用 toLowerCase。另外,如果将来需要生成更长的字符串,可以使用相同的方法而无需更改任何内容。

总结我们将要做的是:

public static String manipulate(String rand){
    String c = rand.substring(0, 1); // where rand is the random alphanumeric generated by your methods, we pick the first char
    c = c.toUpperCase(); // we make it upperCase
    String split = rand.substring(1); // we get the remaining of the string starting from position 1
    split = split.toLowerCase(); // let's apply lowercase on the remaining
    String result = c + split; // join again
    return result;
}

完整代码:

package test;

import java.util.Random;
import java.util.stream.IntStream;

public class AlphaRandom {

    private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    static final Random random = new Random();

    public static void main(String args[]) {
        int length = 5;
        String seq = randomAlphaNumeric(length);
        System.out.println("Random Number Normal  : " + seq);
        IntStream.range(0, 1).forEach(i -> System.out.println("Random Number Streams : " + generateRandomString(random, length)));
    }

    public static String manipulate(String rand){
        String c = rand.substring(0, 1); // where rand is the random alphanumeric generated by your methods, we pick the first char
        c = c.toUpperCase(); // we make it upperCase
        String split = rand.substring(1); // we get the remaining of the string starting from position 1
        split = split.toLowerCase(); // let's apply lowercase on the remaining
        String result = c + split; // join the again
        return result;
    }

    // Using Streams
    private static String generateRandomString(Random random, int length){
        String rand =  random.ints(48, 122)
                .filter(i -> (i < 57 || i > 65) && (i < 90 || i > 97))
                .mapToObj(i -> (char) i)
                .limit(length)
                .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
                .toString();
        return manipulate(rand);
    }

    // Normal
    public static String randomAlphaNumeric(int count) {
        StringBuilder builder = new StringBuilder();
        while (count-- != 0) {
            int character = (int)(Math.random() * ALPHA_NUMERIC_STRING.length());
            builder.append(ALPHA_NUMERIC_STRING.charAt(character));
        }
        return manipulate(builder.toString());
    }
}

输出:

Random Number Normal  : Mwwsz
Random Number Streams : Q1fqk
英文:

The easiest way is that before to return your string (once you have generated it), you take the first letter in order to apply toUpperCase and on the remaining chars, apply toLowerCase. Also, if in the future you will need to generate longer strings, you can use the same method without changing anything.

Summering what we'll do is:

public static String manipulate (String rand){
String c = rand.substring(0,1); // where rand is the random alphanumeric generated by your methods, we pick the first char
c = c.toUpperCase(); //we make it upperCase
String split = rand.substring(1); //we get the remaining of the string starting from position 1
split = split.toLowerCase(); //let&#39;s apply lowercase on the remaining
String result = c+split; //join again
return result;
}

Full Code:

package test;
import java.util.Random;
import java.util.stream.IntStream;
public class AlphaRandom {
private static final String ALPHA_NUMERIC_STRING = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789&quot;;
static final Random random = new Random();
public static void main(String args[]) {
int length = 5;
String seq = randomAlphaNumeric(length);
System.out.println(&quot;Random Number Normal  : &quot; +seq);
IntStream.range(0,1).forEach(i-&gt;System.out.println(&quot;Random Number Streams : &quot; +generateRandomString(random, length)));
}
public static String manipulate (String rand){
String c = rand.substring(0,1); // where rand is the random alphanumeric generated by your methods, we pick the first char
c = c.toUpperCase(); //we make it upperCase
String split = rand.substring(1); //we get the remaining of the string starting from position 1
split = split.toLowerCase(); //let&#39;s apply lowercase on the remaining
String result = c+split; //join the again
return result;
}
// Using Streams
private static String generateRandomString(Random random, int length){
String rand =  random.ints(48,122)
.filter(i-&gt; (i&lt;57 || i&gt;65) &amp;&amp; (i &lt;90 || i&gt;97))
.mapToObj(i -&gt; (char) i)
.limit(length)
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
.toString();
return manipulate(rand);
}
// Normal
public static String randomAlphaNumeric(int count) {
StringBuilder builder = new StringBuilder();
while (count-- != 0) {
int character = (int)(Math.random()*ALPHA_NUMERIC_STRING.length());
builder.append(ALPHA_NUMERIC_STRING.charAt(character));
}
return manipulate(builder.toString());
}
}

Output:

Random Number Normal  : Mwwsz
Random Number Streams : Q1fqk

huangapple
  • 本文由 发表于 2020年9月1日 01:12:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63675247.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定