Error compiling code in eclipse

Asked

Viewed 41 times

0

I have a small problem when compiling this code, after I compile the following error appears:

Exception in thread "main" java.lang.Arrayindexoutofboundsexception: 10

I’ve searched elsewhere, and they said that this error occurs when you’re oversize a vector, but I don’t understand what’s wrong with my code.

public class Questao5Agenda {
    public static void main(String[] args) {

        Scanner inputNumerico = new Scanner(System.in);
        Scanner inputString = new Scanner(System.in);


        Contato [] c1 = new Contato[10];
        int opc;


        do{

             c1[10].Menu();

            opc = inputNumerico.nextInt();

            switch(opc){


            case 1:
                System.out.println("====== Criar Contato ======\n");
                boolean flag= true; 

                for(int i=0; i<c1.length; i++){
                    if(c1[i]==null){   
                        flag= false; 
                        break;      
                    }
                }



                if(flag==false){
                    Questao5Contato c = new Questao5Contato();

                    c.AdicionarContato(); 

                    for(int i=0; i<c1.length; i++){
                        if(c1[i]==null){ 
                            c1[i]= c; 
                        }

                    }

                    System.out.println("Contato adicionado com sucesso !");
                } else{
                    System.out.println("Lista de contatos cheia !");
                }
                break;


            case 2:
                System.out.println("====== Listar Contato ======");

                int i=0;
                if(c1[i]!=null){
                    c1[i].Listar();

                }   
            }



        }while(opc!=5);
    }

}
  • 1

    Counting starts from zero so that C1[10] is outside the limit

  • how do I solve this friend??

1 answer

1

Your mistake is on this line:

c1[10].Menu();

The array c1 has size 10, that is, its valid positions are from 0 to 9, but you are trying to access the tenth position.

  • how do I solve this friend??

  • You got a little complicated because you want to call the method Contato.Menu() without having an object Contato. What does this method do? It needs to be within the class Contato? I don’t quite understand what you’re trying to do in your code.

  • Do the following, edit the question and place the classes Contato and Questao5Contato. But if you want a quick way to solve, depending on what the method Menu() makes you can move it to class Questao5Agenda and declare it as static.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.