【问题标题】:Generating Random Number of Characters生成随机字符数
【发布时间】:2020-04-30 04:37:19
【问题描述】:

我必须创建一个程序来读取要打印的字符数,它会打印随机字符(a-z、A-Z、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');
    }
}

【问题讨论】:

    标签: java random char


    【解决方案1】:

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

    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-01
      • 2011-06-30
      • 1970-01-01
      • 2018-01-25
      • 2017-07-25
      相关资源
      最近更新 更多