有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

与数组索引超出范围有关的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) 个答案

  1. # 1 楼答案

    显然,错误发生在这一行:

          System.out.print(words[wordsRandomSecondOutput] + ".");
    

    words只有3个元素,而从maxtwo生成的随机数最多有13个元素

    也许你本想在打印语句中使用words2而不是words,但你不小心把它颠倒了。一个粗心的小错误