-1

Hello as the title says I want to generate a random text with only characters between 0 and a lowercase z. So far I am able to get values in an area and typecast them to a char which I then save in my array.

import javax.swing.JOptionPane;

class Versuch4{
    public static void main(String[] args){
        char[] zeichen = new char [12];
        String symbol;

        for(int i=0;i<zeichen.length; i++){
            int [] zufall = new int [12];
            zufall[i] = (int)(33+Math.random()*(127-33)); //just used these numbers to test if it works.
            zeichen[i] = (char) zufall[i];
            System.out.print(zeichen[i]);
        }
    }
}

So I know how I can get completely random symbols which is what I am doing above and I know how I can get completely random numbers, but getting random values between both is what I am struggling with. I only saw past questions that used different methods, but for my task I need to use this.

edit: I checked the threads above, but the Math.random() explanation, doesn't explain how I can create random int and string values, only int values within a range. At least I don't see it there. As for the other link it, does show me how I could do it, but I am supposed to use the Math.random() method for this. Sorry if I am just overlooking stuff.

Wojciech Wirzbicki
  • 3,887
  • 6
  • 36
  • 59
Awais
  • 47
  • 6

1 Answers1

0

If your task is to do only with Math.Random(). Here is how you can do

//character set you want to use
public static char[] CHARSET_AZ_09 = "abcdefghijklmnopqrstuvwxyz0".toCharArray();


public static String randomString(char[] characterSet, int length) {
    int charsetLength = characterSet.length;
    char[] result = new char[length];
    for (int i = 0; i < result.length; i++) {
        int randomCharIndex = (int)(Math.random()*charsetLength);
        result[i] = characterSet[randomCharIndex];
    }
    return new String(result);
}
Naghaveer R
  • 2,890
  • 4
  • 30
  • 52
  • I see so instead of using something like 0 and z as boundaries I need to create a char that has all the values that I need and use its content as my boundaries. At least that is how I understood it. Thanks – Awais Dec 12 '18 at 09:08