我得到了一个讲述故事的多数组(基于随机选择的页面、段落和行号)。我需要生成一个密码,其中包含从数组中随机抽取的3个单词。必须给出创建密码的规则(例如:它必须是10个字符的长度,不能重复相同的单词);
这是针对Java的。(步骤1)密码必须由3个单词组成(步骤2)页面、段落和行号是随机选择的,必须使用随机类使用nextInt()生成随机数。(步骤3)使用split()分隔随机字符串中的每个单词。(步骤4)确保在步骤3中从数组中选择一个随机字。(步骤5)为密码创建限制。
我为该限制创建了一个if-else语句。如果不遵循规则,程序必须始终返回(步骤2)
import java.util.Random;
public class passGen {
public static void main(String[] args) {
Random r=new Random();
int pageNum = r.nextInt(story.length);
int paraNum = r.nextInt(story.length);
int lineNum = r.nextInt(story.length);
System.out.print("Password = ");
for (int i = 0; i<3; i++) {
String sentence = story[pageNum][paraNum][lineNum]; // story is the array given
String[] string = sentence.split(" ");
int index = new Random().nextInt(string.length);
String randomWord = string[index];
if (randomWord.equals("a") || randomWord.contains("\n")) {
}
else
System.out.print(randomWord);
}
}
}假设随机生成器从数组中随机选择一句话: story5给出“男孩正在骑自行车\n”。使用split(),然后根据索引随机选择单词,它会选择随机单词"bicycle\n“。我制定了一个规则,如果它选择了一个带新行的单词(' \n '),它必须返回到生成随机数的步骤,并给我一个新的数组,并为我找到一个新的随机单词,直到它找到一个没有\n的单词。例如,假设story6是“他在找乐子”。
我希望输出总是打印一个包含3个随机单词的密码。
password = boyfun.having // fun. is considered as one word with the period.但在某些情况下,当它失败时,它只打印出通过限制('\n')的单词。有时它会打印一个或两个单词,或者当我运行程序时它会给出一个错误。
password = ridingfun
password = boy
Password = Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Assign3Q1.main(passGen.java:123)
// line 123 happens is the String sentence = story[pageNum][paraNum][lineNum];发布于 2019-10-28 11:49:16
不是100%确定你的意思,但我很确定你最终会用你的随机数生成器命中一个越界。
如果你的故事长度是10,nextInt可以选择10,因为它包含了你传递给它的整数。因此,如果您以10结束,然后执行story10,您将得到一个越界,因为索引从0开始。
我建议
r.nextInt(story.length - 1)发布于 2019-10-28 11:54:43
我相信你的问题出在:
int pageNum = r.nextInt(story.length);
int paraNum = r.nextInt(story.length);
int lineNum = r.nextInt(story.length);段落的数量取决于页面,行数取决于页面和段落。我猜你想要的是:
int pageNum = r.nextInt(story.length);
int paraNum = r.nextInt(story[pageNum].length);
int lineNum = r.nextInt(story[pageNum][paraNum].length);关于找到三个符合条件的单词,在连接它们之前,您可以使用streams来实现这一点,而不是使用for循环。目前,不符合您标准的单词将被悄悄忽略:
Stream.generate(this::randomWord)
.filter(w -> !w.contains("\n"))
.limit(3)
.collect(Collectors.joining());否则,您将需要一个字数计数器:
int wordsRequired = 3;
while (wordsRequired > 0) {
String randomWord = ...;
if (!randomWord.contains("\n")) {
System.print...
randomWord--);
}
}另请注意,您可以使用split("\\s")自动删除换行符。这将在包括换行符和制表符的任何空格(而不仅仅是空格)上拆分。
https://stackoverflow.com/questions/58585454
复制相似问题