与数组索引超出范围有关的java错误
我正在尝试生成自动随机生成两个句子的代码,但当我按run时,它会显示:
'Hi Exception in thread "main java.lang.ArrayIndexOutOfBoundsException: Index 12 out of bounds for length 3 at Main.main(Main.java:25)'
我不知道该怎么办,我试着把String[]
变成Long[]
。但我认为这不管用
我猜这与数组的长度有关,但无论如何,我的代码如下:
class Main {
public static void (String[] args) {
int max = 2; //highest random integer. Don't need a minimum.
int maxtwo = 13;
String[] words = {"Hi", "I", "Do"};
String[] words2 = {"like to play football", "enjoy math", "like math", "love football", "don't really like math", "think I'm not very cool", "am very hungry", "have lots of trouble on math", "watch lots of TV", "java is cool", "java's awesome", "I love java", "I want pizza"};
//words2[] prints only if words[1] is selected, not words[0]
Random gen = new Random(); //variable for the first part of the first sentence
int wordsRandomSelection = gen.nextInt(max); //randomly selects a value from String[]
words
System.out.print(words[wordsRandomSelection] + " "); //print string[] with a random value
if (words[wordsRandomSelection] == words[1]) {
int wordsRandomSecondOutput = gentwo.nextInt(maxtwo);
System.out.print(words[wordsRandomSecondOutput] + ".");
}
}
}
你能告诉我错误是什么吗
# 1 楼答案
显然,错误发生在这一行:
words
只有3个元素,而从maxtwo
生成的随机数最多有13个元素也许你本想在打印语句中使用
words2
而不是words
,但你不小心把它颠倒了。一个粗心的小错误