draw:ArrayIndexOutOfBoundsException

时间:2017-10-11 04:26:25

标签: arrays runtime-error processing draw

我正在制作我的第一个文字冒险游戏,但不断向我发出错误。老实说,我不知道发生了什么,或者如何开始解决这个问题。我将发布我的代码和我收到的错误消息。

PFont computer; //creates a variable for the font to be used
int level = 0; //starting level
int branch = 0; //starting level

String[][] textOptions = new String[][]{
  {"Welcome to our text adventure. You are in a room.\n" //new line
  + "It looks like no one has been in here for years.\n"
  + "Would you like to look around? Y/N",""},

  {"You decide to look around the room.\n"
  + "You stand by your initial observation.\n"
  + "The room is covered in a thick layer of dust with cobwebs reaching out in every corner.\n"
  + "There are a few shelves, lined with decaying boxes and files. The terminal you are looking for is nowhere to be seen. \n"
  + "You are now in a hallway. There are two rooms to explore. L/R?",
    "You decide to leave this room. You are now in a hallway.\n"
  + "There are two rooms to explore. L/R?"},

  {"You decide to check the room to the right.",
   "You decide to check the room to the left."},

    };

void setup()
{
  size(1350,700);
  computer = createFont("computer.ttf",25);
}

void draw()
{
  background(0);
  textSize(20);
  textFont(computer);
  text(textOptions[level][branch],10,25);
  fill(0,239,31);
}

void keyPressed()
{
  if(key == 'y')
  {
    println("Player is looking around.");

    if(level < 2)
    {
      level = level+ 1;
      branch = 0;
    }
  }
  else if(key == 'n')
  {
    println("Player decided to leave this room.");

    if(level < 2)
    {
      level = level+ 1;
      branch = 1;
    }
  }

{
    if(key == 'r')
  {
    println("Player has chosen the room to the right.");

    if(level < 3)
    {
      level = level+ 1;
      branch = 2;
    }
  }
  else if(key == 'l')
  {
    println("Player has chosen the room to the left.");

    if(level < 3)
    {
      level = level+ 1;
      branch = 3;
    }
  }
}
}

我一直收到错误代码:

java.lang.ArrayIndexOutOfBoundsException: 3
    at sketch_171010c.draw(sketch_171010c.java:50)
    at processing.core.PApplet.handleDraw(PApplet.java:2437)
    at processing.awt.PSurfaceAWT$12.callDraw(PSurfaceAWT.java:1557)
    at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:316)

它似乎突出显示了textOptions [level] [分支]的绘图部分,但我仍然不明白这意味着什么或如何解决这个问题。任何关于如何做任何事情的帮助或意见将非常感激。谢谢!

1 个答案:

答案 0 :(得分:0)

你应该养成debugging代码的习惯,这样你才能准确理解它正在做什么。

异常是由于尝试访问数组没有的索引引起的。这是一个更简单的例子:

String[] array = {"test"};
String x = array[100];

此代码会抛出ArrayIndexOutOfBoundsException,因为该数组只有一个元素,但我们正在尝试访问索引100.这就是代码中发生的情况。

现在,为什么正在发生的事情需要调试代码。使用一张纸和一支铅笔逐步执行它以跟踪变量的值,或使用Processing IDE附带的调试器。