0

I have a problem in removing String from ArrayList. I can't remove a sentence with spaces between the words.

This is the piece of code I tested

package com.collect;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;

public class collectA {

    collectA() {
        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.add("Hello");
        arrayList.add("World");
        arrayList.add("Have TO Beat all Odds ");
        arrayList.add("AncyMonPatti");
        System.out.println("The Array List Is ");
        System.out.println(arrayList);
        System.out.println("Enter the Name To Delete");
        Scanner inpu = new Scanner(System.in);
        String numtoDel = (String) inpu.next();
        Iterator<String> itr = arrayList.iterator();
        while (itr.hasNext()) {
            if (numtoDel.trim().equals(itr.next().trim())) {
                itr.remove();

            }
        }
        System.out.println(arrayList);
    }

    public static void main(String[] args) {
        new collectA();
    }

}
Tunaki
  • 116,530
  • 39
  • 281
  • 370

1 Answers1

0

To take an string input that will contain whitespace characters, use nextLine() instead of next(). next() does not consider remaining string after whitespace character.

String numtoDel =  input.nextLine();
Shahid
  • 2,258
  • 1
  • 12
  • 23