【问题标题】:How to print a portion of the String, using Random class, in Java?如何在 Java 中使用 Random 类打印字符串的一部分?
【发布时间】:2019-01-17 09:02:56
【问题描述】:

我的目标是使用 Random 类从字符串中打印一部分(5 个字符)。

我已经想出了如何从字符串中随机打印一个字符,但我的目标是打印 5 个字符。到目前为止我的代码:

import java.util.Random;

public class Training {
    public static void main(String[] args) {
        String text = "abcdefghijklmnopqrstuvwxyz";
        Random random = new Random();

        int i = 5;

        System.out.println(text.charAt(random.nextInt(text.length())));
        System.out.println(text.charAt(random.nextInt(text.length())));
        System.out.println(text.charAt(random.nextInt(text.length())));
    }
}

预期的输出必须是字符串中的任意 5 个连续字符。 例如:

hijkl
cdefg
abcde

【问题讨论】:

  • 那么听起来你想从 0 到 text.length() - 5 (不包括上限)中选择一个 starting 点,然后使用子字符串。看看这是否足够的提示。
  • 你会发现random.nextInt(text.length() - 5)很方便。

标签: java


【解决方案1】:
final String text = "abcdefghijklmnopqrstuvwxyz";
final Random random = new Random();
final int length = 5;

for (int i = 0; i < 3; i++) {
    int pos = random.nextInt(text.length() - length)
    System.out.println(text.substring(pos, pos + length));
}

作为创建子字符串的替代方法,您可以打印单独的字符:

for (int i = 0; i < 3; i++) {
    for (int j = 0, pos = random.nextInt(text.length() - length); j < length; j++)
        System.out.print(text.charAt(pos + j));
    System.out.println();
}

【讨论】:

    【解决方案2】:

    生成一个随机整数并用它来打印字符串的子串:

    String text = "abcdefghijklmnopqrstuvwxyz";
    Random random = new Random();
    
    int i = 5;  // define the length of the substring
    
    int index = random.nextInt(text.length() - i);  // get a random starting index
    
    
    System.out.println(text.substring(index, index + i)); // print the substring
    

    【讨论】:

      【解决方案3】:

      你需要一个额外的变量来存储随机值,即

      String text = "abcdefghijklmnopqrstuvwxyz";
      Random random = new Random();
      
      int i = 5, r;
      
      for(int j = 0; j < 3; j++) {
          r = random.nextInt(text.length() - i)
          System.out.println(text.substring(r, r + i));
      }
      

      【讨论】:

        【解决方案4】:

        我认为您可以使用 API substring(int startIndex, int endIndex)。您需要将 startIndex 作为随机数 (endIndex = startIndex + 5) 传递。更多详情可以参考substring

        注意:

        不要忘记检查 startIndex 的值。它可以超过您的字符串长度并引发异常。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-23
          • 2014-08-05
          • 2014-05-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多