【问题标题】:Help for creating a random String创建随机字符串的帮助
【发布时间】:2011-02-28 01:25:03
【问题描述】:

我需要创建一个长度在 6 到 10 之间的随机字符串,但它有时只生成大约 3 到 5 的长度。 这是我的代码。任何人都可以找出问题所在吗? :(

            int lengthOfName = (int)(Math.random() * 4) + 6;
        String name = "";
        /* randomly choosing a name*/
        for (int j = 0; j <= lengthOfName; j++) {
            int freq = (int)(Math.random() * 100) + 1;
            if(freq <= 6){
                name += "a";
            }if(freq == 7 && freq == 8){
                name += "b";
            }if(freq >= 9 && freq <= 11){
                name += "c";
            }if(freq >= 12 && freq <= 15){
                name += "d";
            }if(freq >= 16 && freq <= 25){
                name += "e";                        
            }if(freq == 26 && freq == 27){
                name += "f";
            }if(freq == 28 && freq == 29){
                name += "g";
            }if(freq >= 30 && freq <= 33){
                name += "h";
            }if(freq >= 34 && freq <= 48){
                name += "i";
            }if(freq == 49 && freq == 50){
                name += "j";
            }if(freq >= 51 && freq <= 55){
                name += "k";
            }if(freq >= 56 && freq <= 60){
                name += "l";
            }if(freq == 61 && freq == 62){
                name += "m";
            }if(freq >= 63 && freq <= 70){
                name += "n";
            }if(freq >= 71 && freq <= 75){
                name += "o";
            }if(freq == 76 && freq == 77){
                name += "p";
            }if(freq == 78){
                name += "q";
            }if(freq >= 79 && freq <= 84){
                name += "r";
            }if(freq == 85 && freq == 86){
                name += "s";
            }if(freq == 87 && freq == 88){
                name += "t";
            }if(freq >= 89 && freq <= 93){
                name += "u";
            }if(freq == 94){
                name += "v";
            }if(freq == 95 && freq == 96){
                name += "w";
            }if(freq == 97){
                name += "x";
            }if(freq == 98 && freq == 99){
                name += "y";
            }if(freq == 100){
                name += "z";
            }
        }

【问题讨论】:

  • 我们能否提出更好的解决方案来代替这些嵌套和不可能的条件?
  • 这个请求使用 switch 语句或者更好的数组查找来重写。 (虽然这不是问题的重点)

标签: java string random


【解决方案1】:

if(freq == X &amp;&amp; freq == X+1) 这样的条件总是false

您可能打算使用|| (OR)

【讨论】:

    【解决方案2】:

    你的代码有很多重复相同的问题:

    if(freq == 28 && freq == 29) { ... }
    

    freq equals to 28 AND freq equals to 29 时,您告诉 Java 遵循一个条件。不可能。您将需要使用 OR 运算符:

    if(freq == 28 || freq == 29) { ... }
    

    现在发生的情况是,当 freq 等于那些错误条件中的任何数字时,不会将任何内容添加到您的字符串中并且它会变小。

    【讨论】:

      【解决方案3】:

      你好像写错了。有一次你写

      如果(频率 == 49 && 频率 == 50){ 名称 += "j";

      事实上,这绝不是真的。

      【讨论】:

        【解决方案4】:

        很抱歉,代码写得太差,无法挽救。我推荐这样的东西。

            Random r = new Random(); // just create one and keep it around
            String alphabet = "abcdefghijklmnopqrstuvwxyz";
        
            final int N = 10;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < N; i++) {
                sb.append(alphabet.charAt(r.nextInt(alphabet.length())));
            }
            String randomName = sb.toString();
        
            System.out.println(randomName);
        

        重点是:

        • 使用java.util.Random,特别是nextInt(int n) 在给定范围内获得随机int
          • 不需要时髦的公式
        • 在循环中构建字符串时,使用StringBuilder
        • 使用字母字符串和charAt 为其字母编制索引。

        API 链接

        相关问题


        原代码有问题

        不幸的是,有很多。

        • 循环中的String += 对较长的字符串产生非常差的性能
        • for (int j = 0; j &lt;= lengthOfName; j++)off-by-one-error
        • freq == 7 &amp;&amp; freq == 8 逻辑矛盾
        • 这只是不必要的冗长!
          • 当你写这样的东西时,警告标志应该会响起

        我强烈建议您进行大量小而简单的练习来学习 Java 基础知识。 codingbat.com 很棒;它有数百个,它们会自动评分,因此您会知道您的解决方案何时按预期工作。它有关于逻辑、字符串、数组等的部分。


        关于字母分布不均

        最简单的解决方案是在字母表中有重复项:

        • String alphabet = "aab"; 出现a 的概率是b 的两倍
        • 您可以通过频率表以编程方式生成alphabet
          • 我将把它留作练习(或者如果需要,您可以提出其他问题)

        【讨论】:

        • 感谢您的代码!但是字母不应该以相同的比例分布,所以想不出更好的方法....例如,字母“a”必须以 6% 的机会分布
        • @Max,然后使用长度为 100 的字符串,如“aaaaaabbccc....”(而不是“abcde...”),并使用上面的代码。 polygeneL 使用了“喜欢”这个词,所以我想他希望你做一些工作:-)
        • @Moron,没错。是的,我已经在努力了!!感谢您的评论!
        • 也许stackoverflow.com/questions/2971315/… (Java) 更合适?由于 73883 是 C# .NET,我同意它的概念几乎相同。
        • 不错的答案多基因润滑剂!而白痴不是白痴。
        【解决方案5】:

        这是我的解决方案:

        import java.util.Random;
        
        Random gen = new Random(474587); //put in random seed
        int min = 6;
        int max = 10;
        
        // we want 20 random strings 
        for(int i=0; i < 20; i++){
         int len = min+gen.nextInt(max-min+1);
         StringBuilder s = new StringBuilder(len);
         while(s.length() < len){
          //97 is ASCII for character 'a', and 26 is number of alphabets
          s.append((char)(97+gen.nextInt(26)));     
         }
        
        System.out.println(s.toString());
        }
        

        输出示例:

        zqwloh
        jefcso
        spcnhxyyk
        tzlobaukn
        keyxkn
        cllhsxybz
        ieaudei
        bolfzqlxrl
        scpfcbztyh
        thkfrybffe
        nbspabxjh
        

        【讨论】:

          【解决方案6】:

          仅供参考和完整性,这是一个“简单”(但效率较低)的解决方案,假设字符串中的数字不是一个大问题:

          private static final Random random = new Random();
          
          public static String generateRandomString() {
              return new BigInteger((4 + random.nextInt(3)) * 8, random).toString(36);
          }
          

          这会生成一个随机字符串匹配[a-z0-9],长度为6~10(含)。

          【讨论】:

            【解决方案7】:

            我敢打赌,您不再需要答案,但由于我以前从未回答过堆栈溢出问题,我认为这将是一个很好的热身问题。

            其他人似乎遗漏的一件事是您的代码的频率方面。以下代码将根据您想要的频率创建 10 个长度为 6 到 10 的随机词:

            import java.util.Random;
            
            
            public class Stuff {
            public static void main(String[] args) {
            
                Random rand = new Random();
                int[] freqs = new int[] {6,8,11,15,25,27,29,33,48,50,55,60,62,70,75,77,78,84,86,88,93,94,96,97,99,100};
            
                int numWords = 10;
                for(int i = 0; i<numWords; i++)
                {
                    String word = "";
                    int numLetters = 6 + rand.nextInt(5);
                    for(int j = 0; j<numLetters; j++)
                    {
                        int freq = rand.nextInt(100) + 1;
                        int index = 0;
                        while(freqs[index] < freq) index++;
                        word = word + (char)(97 + index );              
                    }
                    System.out.println(word);
                }
            }
            

            现在,我的问题是你能告诉我这是如何工作的吗?

            JB

            【讨论】:

              【解决方案8】:

              这就是我的想法

              import java.util.*;
              public class RandomString6to10
              
              {
                  public static void main(String[] args)
                  {
                      Random rnd = new Random();
                      Scanner scan = new Scanner (System.in);
                      String alphabets = "abcdefghijklmnopqrstuvwxyz";
                      int min1 = rnd.nextInt(5) + 6;
                      int min2 = rnd.nextInt(3) + 3;
                      System.out.println("How many strings do you want?");
                      int x = scan.nextInt();
              
                      for ( int i = 0; i < x; i++)
                      {
              /* because you didn't tell us when should the generator decide to choose 6-10 or 3-5 
              so I made it random */
              
                          if (rnd.nextBoolean()) 
                          { 
                              min1 = rnd.nextInt(5) + 6;
                              for (int t=0; t < min1; t++)
                              {
                                  int randomString1 = rnd.nextInt(alphabets.length());
                                  System.out.print(alphabets.charAt(randomString1));
                              }
                              System.out.println();
                          }
                          else 
                          {
                              min2 = rnd.nextInt(3) + 3;
                              for (int j=0; j < min2; j++)
                              {
                                  int randomString2 = rnd.nextInt(alphabets.length());
                                  System.out.print(alphabets.charAt(randomString2));
                              }
                              System.out.println();
              
                          }
                      }
                  }
              }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2021-07-12
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2014-10-20
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多