Question 2 ArrayListsjava 20 marks Repeat all of the functio

Question 2. (ArrayLists.java, 20 marks) Repeat all of the functionality of Question 1 but this time use ArrayLists instead of Arrays. Also, add a prompt to allow the user to delete the value at a specified index. Check that the index is valid and if it is not, do nothing. You can do all the work in a single main method.

Solution

import java.util.*;
//Arraylist class defination
public class ArrayLists
{
   public static void main(String args[])
   {
       //Creating arraylist of type integer
       ArrayList<Integer> arr = new ArrayList<Integer>();

       //Adding object in arraylist      
       Scanner sc = new Scanner(System.in);

       System.out.println(\"Enter how many numbers you want: \");
       int no = sc.nextInt();

       System.out.println(\"Enter \" + no + \" Numbers: \ \");
       for(int c = 0; c < no; c++)
           arr.add(sc.nextInt());

       //Getting Iterator from arraylist to traverse elements
       System.out.println(\"\ Entered Numbers: \ \");
       System.out.println(arr);

       System.out.println(\"Enter the Index position to delete: \");
       int pos = sc.nextInt();
       //Checks the validity of the position and removes the data
       if(pos < no)
       {
           arr.remove(pos);
           System.out.println(\"\ After Removing Numbers: \ \");
           System.out.println(arr);
       }
       else
           System.out.println(\"ERROR: Wrong Index Positon\");
   }
}

Ouptut 1:

Enter how many numbers you want:
5
Enter 5 Numbers:

10
20
30
40
50

Entered Numbers:

[10, 20, 30, 40, 50]
Enter the Index position to delete:
5
ERROR: Wrong Index Positon

Output 2:

Enter how many numbers you want:
5
Enter 5 Numbers:

10
20
30
40
50

Entered Numbers:

[10, 20, 30, 40, 50]
Enter the Index position to delete:
2

After Removing Numbers:

[10, 20, 40, 50]

Question 2. (ArrayLists.java, 20 marks) Repeat all of the functionality of Question 1 but this time use ArrayLists instead of Arrays. Also, add a prompt to allo
Question 2. (ArrayLists.java, 20 marks) Repeat all of the functionality of Question 1 but this time use ArrayLists instead of Arrays. Also, add a prompt to allo

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site