Array index out of bounds exception
I am bra开发者_开发百科nd new to Java and was given this piece of code, no explanation just figure it out. Im getting the basics but Im not sure why the error is in place. Im getting
java.lang.arrayindexoutofboundsexception:2
at prealert.listener.<init>.(Listener.Java:26)
at prealert.listener.main(Listener.Java:40)
Thanks in advance for any help.
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);
}
}
}
Take a look at
deviceName = devices[0];
If there are no devices, then this will fail with the exception you see.
I assume that the line in error is: deviceName = devices[0];
which would because devices = JpcapCaptor.getDeviceList();
returns an array with no elements.
Assuming that is true you need to figure out why the array is empty (since you are assuming it will have at least one element) or cope with the fact that it doesn't have any elements and add an if(devices.length > 0) before using it.
I think the problem is in the for loop in the middle. Although the code itself looks fine, you may want to check that devices has something in it first
deviceName = devices[0];
You need to make sure that devices[0]
is an element of that array, because else you will get an index out of bound exception. You could check that by using devices.length
You have to make sure you have at least 3 elements in your array when you call devices[2], maybe your getDeviceList() return an array with size of 0..
精彩评论