2011-09-06 110 views
-1

我是Java新手,并且给出了这段代码,没有解释就明白了。我得到的基础知识,但我不知道为什么错误到位。我得到数组索引超出范围异常

java.lang.arrayindexoutofboundsexception:2 
     at prealert.listener.<init>.(Listener.Java:26) 
     at prealert.listener.main(Listener.Java:40) 

在此先感谢您的任何帮助。

package prealert; 

    import org.apache.log4j.Logger; 
    import org.apache.log4j.PropertyConfigurator; 

    import jpcap.JpcapCaptor; 
    import jpcap.NetworkInterface; 

    public class Listener { 

     private NetworkInterface[] devices; 
     private NetworkInterface deviceName; 
     private Reciever reciever; 
     private JpcapCaptor jpcap; 
     public static Logger log; 


     public Listener() { 
      PropertyConfigurator.configure("log4j.properties"); 
      log = Logger.getRootLogger(); 
      log.debug("Log4j has been initialized"); 
      devices = JpcapCaptor.getDeviceList(); 
      for (int i = 0; i < devices.length; i++) { 
       log.info(devices[i].description); 
      } 
      deviceName = devices[2]; 
      reciever = new Reciever(); 
      try { 
       jpcap = JpcapCaptor.openDevice(deviceName, 2000, true, 100); 
      } catch (Exception e) { 
       log.error("Error with JPcapCreation", e); 
      } 
      reciever.jpcap = jpcap; 
      reciever.start(); 
      new SetBoard(SetBoard.DEFAULT).start(); 
     } 

     public static void main(String args[]) { 
      try { 
       new Listener(); 
      } catch (Exception e) { 
       log.error("ERROR IN THE MAIN METHOD OF LISTENER!", e); 
      } 
     } 
    } 
+0

可能的重复[什么导致java.lang.ArrayIndexOutOfBoundsException,我该如何防止它?](http://stackoverflow.com/questions/5554734/what-c​​auses-a-java-lang-arrayindexoutofboundsexception-and-how-do -i-prevent-it) – Raedwald

回答

3

看看

deviceName = devices[0]; 

如果没有设备,那么这将失败,你看到的例外。

+0

对不起,这是我的错误打印我纠正了我以前的地方[2],我仍然得到相同的错误 – PGFDBUG

+0

如果甚至没有一个设备,那么将不会有3无论是。 –

+0

我有2个设备存在,它列出他们两个然后它会引发错误 – PGFDBUG

0

我假设错误行是:deviceName = devices[0];这将因为devices = JpcapCaptor.getDeviceList();返回一个没有元素的数组。

假设这是真的,你需要弄清楚为什么数组是空的(因为你假设它至少有一个元素),或者应付它没有任何元素并添加if(devices .length> 0)。

0

我认为问题出现在中间的for循环中。尽管代码本身看起来不错,你可能要检查设备具有第一

+1

我相信循环不是问题,因为循环会执行所需的检查... – Alfred

0
deviceName = devices[0]; 

你需要确保devices[0]是数组的元素有东西在里面,因为否则你会得到一个index out of bound exception。您可以检查通过使用devices.length

0

你必须确保你有你的阵列中的至少3个要素,当你调用设备[2],也许你getDeviceList()以0大小返回数组..