0

Im trying but its not good. Here is all code:

    //creating passener object

    Passenger passenger1 = new Passenger(1, "Stefan", "Jankovic", "stefan@gmail.com", 3000);
    Passenger passenger2 = new Passenger(2, "Stefan", "Jankovic", "stefan@gmail.com", 3000);
    Passenger passenger3 = new Passenger(3, "Stefan", "Jankovic", "stefan@gmail.com", 3000);
    Passenger passenger4 = new Passenger(4, "Stefan", "Jankovic", "stefan@gmail.com", 3000);

Adding that passenger into array list:

ArrayList<Passenger> passengerArrayList = new ArrayList<>();
    passengerArrayList.add(passenger1);
    passengerArrayList.add(passenger2);
    passengerArrayList.add(passenger3);
    passengerArrayList.add(passenger4);

Im trying to delete specific passenger from array like this:

@Override
public void deletePassenger(ArrayList<Passenger> passengerList) {

    System.out.println("---Passengers list--");
    for (Passenger tempPassenger : passengerList) {
        System.out.println(tempPassenger);
        System.out.println("If you want to see options menu, enter 6");
    }

    System.out.println("Enter ID of passenger that you want to delete!");
    int id = scanner.nextInt();
    scanner.nextLine();

    System.out.println("---Passengers list--");
    for (Passenger tempPassenger : passengerList) {
        System.out.println(tempPassenger);
        passengerList.remove(id);
    }


}

This is error:

    ---Passengers list--
Passenger{id=1, firstName='Stefan', lastName='Jankovic', email='stefan@gmail.com', balance=3000.0}
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.remove(ArrayList.java:492)
    at com.cv.controllers.PassengerControllerImpl.deletePassenger(PassengerControllerImpl.java:394)
    at com.cv.demo.Main.main(Main.java:66)
Stevan
  • 11
  • 5
  • Can you be a bit more specific about what doesn't work? What is your error? How does the result actually differ from what you expected when you run that code? – Julian Jun 09 '21 at 15:39
  • I'm feeling suspicious about your scanner.newLine() that's directly proceeding your scanner.nextInt(). Why are you asking for a second line of text if you're removing an element by id that you've already asked for? – Julian Jun 09 '21 at 15:42
  • I updated my question with error. I added that `next.Line()` because some bug in intelij or whatever, output is same if I delete it – Stevan Jun 09 '21 at 15:45
  • Am I correct that you're trying to remove a passenger by it's ID? Your variable is called ID, but the remove method you're using I think is trying to go by index in the list. – Julian Jun 09 '21 at 15:50

4 Answers4

1

The problem you have right now is you're just removing an element from the list's index based on user input while you should make sure list is of that size. Second thing, You can't remove an element from the list while browsing it via the forEach loop, you would get a ConcurrentModificationException , read concurrentModificationException. The way to do it would be using an iterator, check

Iterator<Passenger> itr = passengerList.iterator();
while (itr.hasNext()){
    Passenger p = itr.next();
    if (id == p.getId()) {
        itr.remove();
        break;
    }
}
Manish Karki
  • 473
  • 2
  • 11
  • Using Java 8+ you can do it with a single line: `passengerList.removeIf(p->id==p.getId());` – Sascha Jun 10 '21 at 08:26
0

if you want to remove passenger from ArrayList using your passenger id, you can create your own delete function.

public void removeList(ArrayList<Passenger> passengerList, int passengerId) {
    for (int i = 0; i<passengerList.size(); i++) {
        if (passengerList.get(i).getId() == passengerId) {
            passengerList.remove(i);
        }
    }
}

You can use like this

@Override
public void deletePassenger(ArrayList<Passenger> passengerList) {

    System.out.println("---Passengers list--");
    for (Passenger tempPassenger : passengerList) {
        System.out.println(tempPassenger);
        System.out.println("If you want to see options menu, enter 6");
    }

    System.out.println("Enter ID of passenger that you want to delete!");
    int id = scanner.nextInt();
    scanner.nextLine();

    System.out.println("---Passengers list--");
    removeList(passengerList, id);


}
  • You should do it in reverse: `for(int i=size()-1; i>=0; i--)`. Otherwise you skip the next element every time you remove one. – Sascha Jun 10 '21 at 08:25
0

Your code is assuming a correlation between id and list index. Don't!

The code is failing because id is 1-based and list index values are 0-based, so the last Passenger has id 4, but is at index 3. There is no object at index 4, hence the exception.

You have to iterate the list and compare the id value. There are 2 ways:

  • Use removeIf(filter) (Java 8+):

    boolean removed = passengerList.removeIf(p -> p.getId() == id);
    if (! removed)
        throw new IllegalArgumentException("Passenger not found: " + id);
    
  • Use an Iterator (all Java versions):

    boolean removed = false;
    Iterator<Passenger> iter = passengerList.iterator();
    while (iter.hasNext()) {
        Passenger p = iter.next();
        if (p.getId() == id) {
            iter.remove();
            removed = true;
            break; // Stop searching. Remove this if there can be more than one
        }
    }
    if (! removed)
        throw new IllegalArgumentException("Passenger not found: " + id);
    

UPDATE: The above code has been updated as follow-up to this comment:

How to add if statement so if user input ID that doesn't exist show some message?

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • This works, but how to add if statement so if user input ID that doesnt exist show some message – Stevan Jun 09 '21 at 16:15
  • @Stevan In the first case, if you bothered to read the documentation, which I linked to for your convenience, it says *"Returns true if any elements were removed"*. In the second case, you can easily add your own boolean variable. – Andreas Jun 09 '21 at 17:03
-1

It seems like it should remove that specific passenger from the arraylist. Id and index do not relate. Try checking your list after removal:

for (Passenger tempPassenger : passengerList) {
       if(tempPassenger.id==id){
              passengerList.remove(tempPassenger);
       }
         
    }
       
    

for (Passenger tempPassenger : passengerList) {
        System.out.println(tempPassenger);
    }
  • Yes, you are not indexing properly. You have added 4 passengers to your arraylist, but remember indexing begins at 0. Thus passenger 1 will be at index 0. @Stevan – Candyfloss Jun 09 '21 at 15:48
  • How I can fix this, I dont know how to solve this from your answer. Edit, okey, I fixed it – Stevan Jun 09 '21 at 15:50
  • Another problem, when I try to delete last index im getting `indexOutOfBounds` `index 1: size: 1` – Stevan Jun 09 '21 at 15:54
  • `id` is not related to the index. E.g. removing id 2, then id 4, would be `remove(1); remove(3);`, except that after `remove(1);` the index of id 4 is now 2, not 3. – Andreas Jun 09 '21 at 15:56
  • Oh, yes @Andreas is correct. It might work at the start but eventually once you start adding or deleting, index and id won't correlate. You need to loop through finding the passenger matching that id and then delete. – Candyfloss Jun 09 '21 at 16:03