【问题标题】:How to get multiple outputs of random letters?如何获得随机字母的多个输出?
【发布时间】:2015-03-01 19:58:03
【问题描述】:

我有一个程序,我需要它来询问用户一个词,例如你好,然后要求一个模式,例如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 个不同的随机字母输出? p>

【问题讨论】:

  • 你的解决方案有什么问题?
  • “不同的输出”到底是什么意思?永远不要在同一个词中使用相同的字母?如果单词足够大,需要超过 26 个字符怎么办?

标签: java string random output


【解决方案1】:

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

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

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

【讨论】:

  • 你能不能快点把userInput设置为3。
【解决方案2】:

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

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

您的字符串将出现在结果中。异常处理留给读者作为练习。

【讨论】:

    猜你喜欢
    • 2016-09-09
    • 2015-05-03
    • 2013-01-11
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 2011-05-06
    • 1970-01-01
    • 2011-01-29
    相关资源
    最近更新 更多