如何使用Math.random生成0-z之间的随机值?

时间:2018-12-12 08:25:01

标签: java arrays random

您好,如标题所示,我想生成一个随机文本,仅包含介于0和小写字母z之间的字符。到目前为止,我能够在一个区域中获取值并将其类型转换为一个char,然后将其保存在数组中。

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

因此,我知道我如何才能获得完全随机的符号,这也是我在上面所做的事情,而且我知道如何获得完全随机的数字,但是我很难在两者之间获得随机值。我只看到过去使用不同方法的问题,但是对于我的任务,我需要使用它。

edit:我检查了上面的线程,但是Math.random()的解释并没有解释如何创建随机的int和字符串值,仅创建范围内的int值。至少我在那里看不到。至于其他链接,确实显示了我该怎么做,但是我应该为此使用Math.random()方法。抱歉,如果我只是忽略东西。

1 个答案:

答案 0 :(得分:0)

如果您的任务仅是处理Math.Random()。这是你可以做的

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