Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

276
Visualizações
Storing elements of array entered one by one, to be displayed altogether later

Thanks for the help so far. I am making a menu in java, the first option requires the user to enter a number and have it added to an array, after entering the number, they have to choose option 1 again to enter the next number to be added to the array, they cannot be added all at once, this needs to happen up to 5 times. My code is only storing the most recent number given and displaying it when I select option 2: image of terminal

Is there a way I can add and store each element to the array one by one and then display all that was input altogether when I select option 2 from my switch statement?

            //Menu loop
            int myMonths[] = new int[5];
            while(choice !=6){

                switch (choice){
                case 1:
                //int n = number of projects
                int n=1;
                Scanner sc = new Scanner(System.in);
                System.out.println("How many months was your project?");
                for(int i=0; i<n; i++){
                    //read the elements of the array
                    myMonths[i]=sc.nextInt();}
                break;
                case 2:

                System.out.println("Choice 2: Display all items");
                for(int i=0; i < myMonths.length; i++){
                    System.out.println(myMonths[i] + " ");}
                break;
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You are only assigning one project outside of the loop. By the time you ask them, the length of the for-loop is only int n = 1

            //int n = number of projects
            int n=1;
            Scanner sc = new Scanner(System.in);
            System.out.println("How many months was your project?");
            for(int i=0; i<n; i++)   // THIS IS LIKE i < 1
            {
                //read the elements of the array
                myMonths[i]=sc.nextInt();
            }
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda