简体   繁体   中英

Array index out of bounds exception

I am brand 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

调用devices [2]时,必须确保数组中至少有3个元素,也许getDeviceList()返回的数组大小为0。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM