【问题标题】:ArrayList with integers and user input具有整数和用户输入的 ArrayList
【发布时间】:2019-09-17 13:50:55
【问题描述】:

所以我有一个学校作业,我被困住了,想要一些关于如何处理它的指导。任务是:

本实验的目的是操作整数的 ArrayList。任务是 编写一个程序: 1. 声明一个整数的 ArrayList。 2. 实现以下方法:  一种显示菜单的方法。菜单应该在每个之后显示 完成菜单选择。 1.添加元素 2.在特定索引处添加元素 3.删除特定索引处的元素 4. 显示最小值、最大值、总和和平均值 5. 搜索 6. 退出

所以我这里已经有代码了

import java.util.Scanner;

public class ArrayList
{
    static int count;
    static Scanner kb = new Scanner(System.in);

    public static void main()
    {
        int item=0;
        ArrayList numArray = new ArrayList();
        count=0;


        while (item !=6)
        {
            menu();
            item=kb.nextInt();
            if (item==1)
                addElements(numArray);
            //else if (item==2)
                //printArray(numArray);
        }

        System.out.println("Goodby!");

    }

    public static void menu()
    {
        System.out.println("1. Add Elements");
        System.out.println("2. Add an element at a specific index");
        System.out.println("3. Remove an element at a specific index");
        System.out.println("4. Show min, max, sum and average");
        System.out.println("5. Search");
        System.out.println("6. Exit");
        System.out.print(": ");
    }

    public static void addElements(ArrayList arr)
    {
        count=0;
        int num;
        System.out.print("Enter integer values to fill the arrayList -vevalue to stop: ");
        do
        {
            num = kb.nextInt();
            if (num >=0)
            {
                arr.add(count);
                count++;
            }
        } while (num > 0);

    }

所以基本上当你在控制台输入 1 时,它会提示你将整数添加到我一开始建立的空数组列表中。我只是在第一部分遇到了有关如何将用户输入添加到数组列表的语法的问题。

【问题讨论】:

  • arr.add(count); 似乎是这里的问题。您只是将“计数”变量添加到数组列表中,而希望将您从用户那里获取的数字 num = kb.nextInt(); 添加到数组列表中。

标签: java arrays arraylist menu java.util.scanner


【解决方案1】:
  1. 您正在使用原始类型的 ArrayList。更安全的方法是使用泛型类型,您不能只添加所有内容:

ArrayList<Integer> numArray = new ArrayList<Integer>();

  1. 要将用户输入添加到数组中,您必须添加num,因为这是您保存用户输入的整数:

只需替换 arr.add(count);arr.add(num);

【讨论】:

    猜你喜欢
    • 2014-02-07
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    相关资源
    最近更新 更多