Home > OS >  Im trying to delete elements of an arraylist via inputs but the program stops at the third input, I
Im trying to delete elements of an arraylist via inputs but the program stops at the third input, I

Time:12-10

Im trying to delete elements of an arraylist via inputs but the program stops at the third input, I would like to know why it does that.

Scanner scan = new Scanner(System.in);

int[] array = {15, 30, 25, 19, 30, 40}; //1d array 

for (int i = 0; i< array.length; i  ) //List out the original arraylist
{ 
    System.out.print(array[i]  " ");
}

List<Integer> list = Arrays.stream(array).boxed().collect(Collectors.toList()); //converts into arraylist

System.out.print("\nEnter an element to delete:");

    for (int i = 0; i < list.size(); i  ) 
    { 
        int input = scan.nextInt();
    
        if (!list.isEmpty()) 
        {
            for (int j = 0; j < list.size(); j  ) 
            { 
                list.remove(Integer.valueOf(input)); //input for choosing which element should be remove
                System.out.print(list.get(j)  " ");
            }
            System.out.print("\nEnter an element to delete:");                  

        }
            else
            {
                System.out.print("\nArray is empty");
                break;              
            }
        
    }
}

}

CodePudding user response:

There are a couple of problems with your program.
The condition of for loop was not correct and some other minor issues.

Here, is a better version of your program:

public static void main(String[] args) {
    int[] array = {15, 30, 25, 19, 30, 40}; //1d array
    Scanner scan = new Scanner(System.in);
    List<Integer> list = Arrays.stream(array).boxed().collect(Collectors.toList()); //converts into arraylist

    while (!list.isEmpty()) {
        System.out.println(list);
        System.out.print("\nEnter an element to delete:");
        int input = scan.nextInt();
        list.remove(Integer.valueOf(input)); //input for choosing which element should be remove
    }
    if(list.isEmpty()){
        System.out.println("Array is empty.");
    }
}
  • Related