Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2

0

Can someone help me with this problem? create this simple example to test what I learned recently in java programming, but for some reason when I try to execute the problem I get an error even if I have no part pointed, can someone help me?

public static void main(String[] args) {

        String[] hembra = new String[2];

        String macho[] = new String[2];

        macho[0] = "macho";
        macho[1] = "Hombre";
        macho[2] = "masculino";
        hembra[0] = "hembra";
        hembra[1] = "mujer";
        hembra[2] = "femenino";

        String genero = JOptionPane.showInputDialog("Introduce tu genero");

        for (int i = 0; i < 2; i++) {

            if (genero.equals(hembra[i])) {

                String altura = JOptionPane.showInputDialog("Introduce tu altura en cm");

                int peso1 = Integer.parseInt(altura);

                System.out.println("tu peso ideal es: " + (peso1 - 120) + "kilos");

            }
        }
        for (int a = 0; a < 2; a++) {
            if (genero.equalsIgnoreCase(macho[a])) {
                String altura2 = JOptionPane.showInputDialog("Introduce tu altura en cm");

                int peso2 = Integer.parseInt(altura2);

                System.out.println("tu peso ideal es: " + (peso2 - 110) + "kilos");

            }

            if (genero.equalsIgnoreCase(hembra[a])) {
                String altura3 = JOptionPane.showInputDialog("Introduce tu altura en cm");
                int peso3 = Integer.parseInt(altura3);
                System.out.println("tu peso isea es: " + (peso3 - 120) + " Kilos");

            }
        }

    }
}
    
asked by Noel San 12.07.2017 в 14:38
source

1 answer

0

Well as your colleagues commented, your problem is in the size that you define the array since you need an array of size 3 and not 2.

    String[] hembra = new String[3];

    String[] macho = new String[3];

You should also change the ranges of the for to go through the 3 elements per array.

In your case I would recommend that you fix the arrays directly and to avoid defining the size you could go through the array with a foreach

    String[] macho = {"macho","hombre","masculino"};

    String[] hembra = {"hembra","mujer","femenino"};

    for(String genero: macho){
        //stuff
    }

    for(String genero: hembra){
        //stuff
    }
    
answered by 12.07.2017 в 17:10