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;
CodePudding user response:
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();
}