存储数组的元素逐一输入,以后将完全显示
感谢到目前为止的帮助。我正在Java中制作菜单,第一个选项要求用户输入一个数字并将其添加到数组中,输入数字后,他们必须再次选择选项1才能输入下一个数字要添加到数组中,不能一次添加它们,这需要发生长达5次。 我的代码仅存储最新的数字并在选择选项2时显示它。 终端的图像
是否有一种方法可以将每个元素添加到数组中然后从切换语句中选择选项2时完全显示输入的所有内容?
//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;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您仅在循环之外分配一个项目。当你问他们时,for 循环的长度只有 int n = 1
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