1

So I have a school assignment that I am stuck on and would like some guidance on how to approach it. The task is:

The purpose of this lab is to manipulate an ArrayList of integers. The assignment is to write a program that: 1. Declares an ArrayList of integers. 2. Implements the following methods:  A method that displays a menu. The menu should be displayed after each completed menu selection. 1. Add elements 2. Add an element at a specific index 3. Remove an element at specific index 4. Show min, max, sum and average 5. Search 6. Exit

So I already have the code here

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);

    }

So basically when you input 1 in the console, itll prompt you to add integers to the empty arraylist I established in the beginning. Im just having trouble with the first part alone with the syntax on how to get the user input to be added to the array list.

  • `arr.add(count);` seems to be the problem here. You are just adding the 'count' variable to your array list, while the desire is to add the number you took from the user, `num = kb.nextInt();` to your array list. – BeUndead Sep 17 '19 at 13:56
  • This answer. [ArrayList of int array in java](https://stackoverflow.com/questions/10477628/arraylist-of-int-array-in-java) – superup Sep 17 '19 at 14:40

1 Answers1

1
  1. You are using the raw type of ArrayList. The safer method is using a generic type, where you can't just add everything:

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

  1. To add the user input to the array, you have to add num since this is the integer you saved the user input in:

just replace arr.add(count); with arr.add(num);

divjo
  • 62
  • 6