Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

257
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!