首页 > 解决方案 > 生成随机字符数

问题描述

我必须创建一个读取要打印的字符数的程序,它将打印随机字符(az、AZ、0-9 和字符,如!、&、$ 等)。并且要打印的第一个字符不能是数字(0-9)。

因此,示例输出如下:

变量的长度?20

a5fTnO$akP_a12BahsiO

这就是我到目前为止所拥有的,但我被困住了,不知道我还能做些什么来让它发挥作用。我也不确定我是否走在正确的轨道上。

我会更容易创建一个字符串,然后从字符串中获取随机字符(如果可能的话)?


import java.util.Scanner;

public class VariableNameRandomGen{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);

        System.out.print("Length of the variable? ");
        int num = sc.nextInt();

        final int noOfChars = num;
        final int charsPerLine = num;

        for(int i = 0; i < noOfChars; i++){
            char ch = getRandomCharacter();

            if((i+i) % charsPerLine == 0)
                System.out.println(ch);
            else
                System.out.print(ch);
        }
    }

    public static char getRandomCharacter(char ch1, char 2){
        return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
    }

    public static char getRandomUpperCaseLetter(){
        return getRandomCharacter('A', 'Z');

    }

    public static char getRandomDigitCharacter(){
        return getRandomCharacter('0', '9');
    }
}

标签: javarandomchar

解决方案


您可以使用示例字符串包含您想要的所有字符:

final static String SAMPLE = "abcd... xyzABCD...XYZ ()?!;"
final static String NUM = "0123456789";
public static char getRandomCharacter(String s){
    return s.charAt( new Random(s.lenght()).nextInt());
}

而在主要

String rs = "" + getRandomCharacter(SAMPLE);
for(int i = 1; i < noOfChars; i++){
        char ch = getRandomCharacter(SAMPLE + NUM);
        rs+= ch;
    }
System.out.print(rs);

推荐阅读