我的目标是使用 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
生成一个随机整数并使用它来打印字符串的子字符串:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句