简体   繁体   中英

how to remove specific object in an ArrayList while using a scanner in java

I'm trying to remove a MemberPlayer(object) from my ArrayList(memberList) thorugh my input(scanner)

I have tried looking around google and Stack but can't seem to find anything that uses scanner.

    public void removeMember(){
    System.out.println("Which MemberPlayer are you looking for?:");
    System.out.print("Input first name: ");
    String fName = input.nextLine().toUpperCase();
    System.out.print("Input last name: ");
    String lName = input.nextLine().toUpperCase();

    for (MemberPlayer m: memberlist){
        if(m.getFirstName().contains(fName) && m.getLastName().contains(lName)) {
            System.out.println();
            System.out.println("This MemberPlayer exist:");
            System.out.println(fName + " " + lName);

            System.out.print("Do you want to remove this MemberPlayer?  [yes/no]");
            input.nextLine().toUpperCase();
            if (input.equals("Yes")) {
                memberlist.remove(); //I can't figure out how to write this line?
            }else{
                break;
            }
        }else {
            System.out.println();
            System.out.println("This MemberPlayer doesn't exist");
            System.out.println();
            break;
        }
    }
}

I read my memberlist from a file.txt with the following info: first name, last name, age and team.

ANDERS
ANDERSEN 23 1

BERT BERSEN 16 2

HANS HANSEN 25 1

TIM TIMSEN 20 2
MORTEN MORTENSEN 34 1

You need to use List#remove() , from the docs :

boolean remove(Object o)

Removes the first occurrence of the specified element from this list, if it is present (optional operation). If this list does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).


Also, you don't need a for-loop here. Your method can be simplified to a much more OO approach :

public void removeMember() {
    System.out.println("Which MemberPlayer are you looking for?:");
    System.out.print("Input first name: ");
    String fName = input.nextLine().toUpperCase();
    System.out.print("Input last name: ");
    String lName = input.nextLine().toUpperCase();

    // create an object with input received
    MemberPlayer m = new MemberPlayer(fName, lName);

    // use contains of List
    if (memberlist.contains(m)) {
        memberlist.remove(m);
    } else {
        System.out.println("This MemberPlayer doesn't exist");
    }
}

Make sure you override the .equals() and .hashcode() methods in MemberPlayer .

I recommend using an Iterator for this, as using the List.remove(Object o) can throw the ConcurrentModificationException as you are changing the state of the object while iterating.

So Iterator.remove() will be a safe bet. From the Java SE 1.8 docs:

Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics .

So removing an object directly from the List using List.remove() will cause unpredictable iteration and throw ConcurrentModificationException while iterating it.

If you are not iterating then it is fine to use the List.remove(Object o) to remove the object from the List .

//Initializes the iterator, checks if next element is present by calling Iterator.hasNext()
for(Iterator<MemberPlayer> itr = memberList.iterator(); itr.hasNext(); ){
         m = itr.next(); //The current element of the List
         if(m.getFirstName().contains(fName) && m.getLastName().contains(lName)) {
            System.out.println();
            System.out.println("This MemberPlayer exist:");
            System.out.println(fName + " " + lName);

            System.out.print("Do you want to remove this MemberPlayer?  [yes/no]");
            input.nextLine().toUpperCase();
            if (input.equals("Yes")) {
                 itr.remove(); //Removes the current element if the condition is satisfied.
            }else{
                 break;
            }
         }else {
             System.out.println();
             System.out.println("This MemberPlayer doesn't exist");
             System.out.println();
             break;
         }
 }

Remember that you cannot remove a Collection<T> element while you're iterating it using the for-each loop. In that case a ConcurrentModificationException might be thrown.

You need to explicitly use an Interator<T> or a ListIterator<T> , depending on the usecase.
A ListIterator allow also insertion of elements or setting of elements.

for (final Iterator<MemberPlayer> iterator = memberList.iterator(); iterator.hasNext();) {
   final MemberPlayer m = iterator.next();

   if (m.getFirstName().contains(fName) && m.getLastName().contains(lName)) {
      ...

      iterator.remove();
   }
}

this is what ended up working for me after some trial and error.

public void removeMember()throws FileNotFoundException {
    System.out.println("Which MemberPlayer are you looking to remove?:");
    System.out.print("Input first name: ");
    String fName1 = input.nextLine().toUpperCase();
    System.out.print("Input last name: ");
    String lName2 = input.nextLine().toUpperCase();

    for (MemberPlayer m : memberlist){

        if (m.getFirstName().equals(fName1) & m.getLastName().equals(lName2)) {
            System.out.println();
            memberlist.remove(m);
            System.out.println("You removed: "+m.getFirstName()+" "+m.getLastName());
            System.out.println();
            saveMember();
            break;
        } else {
            System.out.println();
            System.out.println("This MemberPlayer doesn't exist");
            System.out.println();
            break;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM