we will perform some basic operations on arraylists: read input using a scanner instance and then perform an operation on an arraylist depending on the input. each line of input has 2 or 3 numbers. the first number is a command {0, 1, 2, 3}. perform an action based on the command. all inputs are integers. commands: 0 : add an element to end of arraylist. (for example, the input 0 7 means add the element 7 to the end of the arraylist.) 1 : reset the element at given index. (for example, 1 4 5 means reset index 4 to be the element 5, if it exists.) 2 : remove an element at a particular index. (for example, 2 6 means remove the element at index 6, if it exists.) 3: print the contents of the arraylist and exit the program.

Respuesta :

Java program that load data on structure type ArrayList, adds, removes, replaces elements from the list according to command. The output and the code image is attached.

Java code

import java.util.ArrayList;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

ArrayList<Integer> lsta = new ArrayList();

Scanner sc = new Scanner(System.in);

  • //Define variables

int i;

int vlu;

int vlu1;

int comd;

do {

do {

  • //Input comand

System.out.print("Comand: ");

comd = sc.nextInt();

} while  (!(comd>=0 & comd<=3));

switch (comd) {

 case 0 :

    System.out.print("Value: ");

    vlu = sc.nextInt();

  •  //add the list to the end of the ArrayList

    lsta.add(vlu);

       break;    

   case 1:

       do {

    System.out.print("Value 1: ");

    vlu = sc.nextInt();

    } while (vlu > lsta.size());

    System.out.print("Value 2: ");

    vlu1 = sc.nextInt();

  • //reset the element at given index

    lsta.set(vlu,vlu1);

       break;

   case 2:

    do {

    System.out.print("Value: ");

    vlu = sc.nextInt();

    } while (vlu > lsta.size());

  • //remove an element at a particular index

    lsta.remove(vlu);

       break;

 }

} while (!(comd==3));

  • //Print the contents of the arraylist and exit the program

System.out.println("The contents of the arraylist:" + lsta);  

}

}

To learn more about Java method ArrayList  see: https://brainly.com/question/23189171

#SPJ4

Ver imagen megatokay
Ver imagen megatokay