如何获得随机字母的多个输出?

时间:2015-01-03 21:50:51

标签: java string random output

我有一个程序,我需要它来询问用户一个单词,例如你好,然后要求一个模式,例如2然后取出该单词并拆分字符并在单词的字母之间放置随机字母,因此在这种情况下,用户模式为3,因此hello将输出为**h**as**e**rg**l**ty**l**oh**o**。所以我有一个部分,我要求用户说一个单词,然后用System.out.print(userWord.charAt(0));

填充单词的字符

我只需要知道每次在字符之间生成随机不同的字母。生成字母的代码部分是:

public static void main (String[] args)
{

    int cipherchoice = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter a number!"));

    int z;
    String  mixedarray1 [] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",};
    int x = mixedarray1.length;  // determines the length of mixedarray
    String[] myarray = new String [cipherchoice]; // create a new arracy to be coded

    for (int i = 0; i < cipherchoice; i++)  // loop equal size of coded array
    {  
      z = (int)(Math.random()*x); //  to create a random index value from mixedarray
      myarray[i] = mixedarray1[z]; // assigned myarray a random index value from mixedarray
      System.out.print (myarray [i]); // prints results using print (not println)
    }
}

所以我的输出是System.out.print(myarray [i]);那么你如何得到多个不同的输出(例如,如果用户在另一部分代码中输入5 你将如何得到5个不同的随机字母输出?

2 个答案:

答案 0 :(得分:0)

将您的代码放入方法中并将其调用n次。例如。

void printRandomLetter() {
    ... the code you posted ...
}

...
void someOtherMethod() {
    for (int i = 0; i < userInput; i++) {
        printRandomLetter();
    }
}

答案 1 :(得分:0)

使用the random.org service via HTTP,通过Java发出对https://www.random.org/strings/?num=10&len=8&digits=on&upperalpha=on&loweralpha=on&unique=on&format=html&rnd=new的HTTP GET请求,如下所示:

URL url = new URL("https://www.random.org/strings/?num=10&len=8&digits=on&upperalpha=on&loweralpha=on&unique=on&format=html&rnd=new");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("GET");
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null) {
     result += line;
}
rd.close();

你的字符串将在结果中。异常处理留给读者练习。