Skip to content
Advertisement

Appstore based app which will save the list of apps

So, I am trying to build a list of the names of all the apps which a client will add/remove. Therefore, I tried to use a LinkedList and coded the following: –

   package academy.learnprogramming;

   

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class AppStore {


    private List<String> ListofApps = new LinkedList <String> ();

    public void addApp (String Apptobeadded) {
        ListIterator<String> apps = ListofApps.listIterator();
        while (apps.hasNext()) {
            int comparision = apps.next().compareTo(Apptobeadded);
            if (comparision == 0) {
                System.out.println("There is already a similar app. Please change the name");
            } else
                apps.add(Apptobeadded);


        }


    }
        public void removeApp (String Apptobedeleted) {
        ListIterator <String> apps = ListofApps.listIterator() ;
        while (apps.hasNext()) {
            int comparision = apps.next().compareTo(Apptobedeleted);
            if (comparision == 0) {
                int appindex = ListofApps.indexOf(Apptobedeleted);
                ListofApps.remove(ListofApps.remove(appindex));
            }




    }}

    public void showalltheapps (){
        System.out.println(ListofApps);
    }


}

Since I am just trying to learn, I assumed that Apps are just Strings.

The problem I am facing right now is that the output shows absolutely nothing when I tried to use the showalltheapps command.

Where did I go wrong and what can I change in order to make my code usable.

Advertisement

Answer

The problem is that apps.hasNext() return false when your list is empty. And your list is initially empty. So the addApp and removeApp methods never do anything if you list is empty.

Add empty list checks to your code, for example:

public void addApp(String Apptobeadded) {
        ListIterator<String> apps = ListofApps.listIterator();
        
        // handling empty list
        if (ListofApps.isEmpty()) {
            apps.add(Apptobeadded);
            return;
        }

        while (apps.hasNext()) {
        // rest of your code
        // ...
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement