Generating Random Number of Characters

Tags: , ,



I have to create a program that reads in the number of character to be printed, and it will print random chars (a-z, A-Z, 0-9 and characters like !, &, $, etc). And the first character to be printed cannot be a number (0-9).

So an example output would be like:

Length of Variable? 20

a5fTnO$akP_a12BahsiO

This is what I have so far, but I’m stuck and don’t know what else I can do to make it work. I’m not sure whether I’m on the right track either.

Would it be easier for me to create a string of the characters and then just get random characters from the string (if that’s possible)?

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

Answer

You can use the sample string contains all char you want:

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

And in main

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


Source: stackoverflow