Question

My code for deleting a player of a doubly linked list works right, but the System.out.print statements don't. I placed System.outs.print statements before the removeFirst and removeLast because I don't know of a way to output the data that was removed in the nodes so I print it out before I remove. I know my current method is bad design but I'm unsure of what function to use.

What conditions do I check for in an if-statement to see if the node has removed successfully?

    else if (mChoice.startsWith("4")) {
    System.out.println("What do you want to delete?");

    mChoice = in.nextLine();

    if (mChoice.contains("first")) {
       System.out.println("Removed first player " + rBook.mHead.getData());
       rBook.removeFirst();
    }

    else if (mChoice.contains("last")) {
       System.out.println("Removed last player " + rBook.mHead.mPrev.getData());
       rBook.removeLast();
    }

    else {

       rBook.remove(rBook.searchByName(mChoice));

       // System.out.println(rBook.get() + " removed.");  this line

    }
Was it helpful?

Solution

If you dont want to change your Player class and its functions try this:

    else if (mChoice.startsWith("4")) {
    System.out.println("What do you want to delete?");

    mChoice = in.nextLine();
    Player deleted;
    if (mChoice.contains("first")) {
       deleted = rBook.mHead.getData();
       rBook.removeFirst();
       System.out.println("Removed first player " + deleted);
    }

    else if (mChoice.contains("last")) {
       deleted = rBook.mHead.mPrev.getData();
       rBook.removeLast();
       System.out.println("Removed last player " + deleted );

    }

    else {
       deleted = rBook.searchByName(mChoice);
       rBook.remove(searchByName(mChoice));
       System.out.println(deleted + " removed.");

    }

OTHER TIPS

I would suggest that you modify your remove() function to return the element you just removed. So the code you're looking at would look like:

Player deleted = rBook.remove(rBook.searchByName(mChoice));
System.out.println(deleted.get() + " removed.");

If you want to store which elements of the list have been removed (to print or undelete them later, for example), then a better design would be either

  • only flagging these elements as removed, or
  • moving them into another, "history" list.

Which of these solutions is better depends on the problems you want to solve.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top