Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 2 of 3 FirstFirst 123 LastLast
Results 26 to 50 of 62

Thread: ArrayList<> String searches and loops

  1. #26
    Member
    Join Date
    Jul 2021
    Posts
    40
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: ArrayList<> String searches and loops

    Now I'm trying to Write a method called getAppsByAuthor that takes a String parameter and returns a list of apps by the given author. If there are no apps with that author, return an empty list (not null). Do not print anything in this method. I have a couple questions:
    1. I'm not sure how to return an empty list rather than null.
    2. I can't get my method to return the list of apps by the given author. My method finds them, but doesn't return them. Here's the code.

    public ArrayList<App> getAppsByAuthor(String name)
    {
       ArrayList<App> appsByAuthor = new ArrayList<App>();
          for(App app : appList) {
             if (app.getAuthor() != (name)) {
     
             }
     
             if (app.getAuthor().equals(name)) {
                 appsByAuthor.add(app);    
             }
        }
           return appsByAuthor;
     
    }

  2. #27
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: ArrayList<> String searches and loops

    What happens when the code is compiled?
    If there are no compiler errors, what happens when the code is execute?

    My method finds them, but doesn't return them.
    How do you know that?
    Where is the code that tests this method?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #28
    Member
    Join Date
    Jul 2021
    Posts
    40
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: ArrayList<> String searches and loops

    I know it finds them because when I search for the author name, if there are apps created by that name, a BlueJ method result box appears. It says the name of the method and the name that I searched and shows an arrow that you can follow for further information. If I click the arrow it takes me to an Object Data box, when I click that arrow, it brings up a box that says App then the fields below are filled in with App name, author, price, and rating. You want me to repost the entire source code? I can

  4. #29
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: ArrayList<> String searches and loops

    I know it finds them
    Ok, then there is no problem with the method. You have tested it and it works for you.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #30
    Member
    Join Date
    Jul 2021
    Posts
    40
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: ArrayList<> String searches and loops

    Noooo. Only part of it. You asked me how I knew that the method found the apps, I responded. I don't know how to make it return the apps that were created by the given author, and I don't know how to return an empty list. I looked it up, but really don't grasp how to write it, or if I need to use a java util.package to do so. I can re-post the entire source code if you want so that you can see everything I see.

  6. #31
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: ArrayList<> String searches and loops

    Why do you think there is a problem?
    Can you compile and execute the code and print out the results and post those results so I can see what you see when the code is executed.

    Also post the code that calls the methods and prints out the results for the tests you are doing.
    Normally that would be in the main() method.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #32
    Member
    Join Date
    Jul 2021
    Posts
    40
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: ArrayList<> String searches and loops

    I think there's a problem because when I execute that method the dialog box in BlueJ doesn't show the names of the apps by the given author. Also, I haven't been able to return an empty list.

    import java.util.ArrayList;
    import java.util.Scanner;
    import java.util.Collections;
     
    /**
     * An app store containing apps
     */
     
    public class AppStore
    {
        private String appStoreName;
        private ArrayList<App> appList;
     
        /**
         * Create an app store with the given name
         * @param name the name of this app store
         */
        public AppStore(String name)
        {
            appStoreName = name;
            appList = new ArrayList<App>();
        }
     
        /**
         * Populate the store with a few apps.
         * Use this method to make testing easier. After creating an AppStore,
         * call this method to populate the apps, and then test your methods.
         */
        public void populateApps()
        {
            addApp("Pandora Music", "Pandora", 0);
            addApp(new App("Minecraft", "Mojang", 6.99, 3));
            addApp(new App("Coinbase", "Coinbase Global Inc.", 0, 0)); 
            addApp(new App("Telegram Messenger", "Telegram FZ LLC", .99, 0));
            addApp(new App("IPTV Extreme", "Paolo Turatti", 1.99, 0));
     
        }
     
        /**
         * Add the given app to the app store
         * @param anApp an app to add
         */
        public void addApp(App anApp)
        {
            appList.add(anApp);
        }
     
        /**
         * Create an app with the given name, author, and price and add it to the store.
         * The app starts out unrated.
         * @param name name of the app
         * @param author the app author
         * @param price the price of the app
         */
        public void addApp(String name, String author, double price)
        {
            appList.add(new App(name, author, price));
        }
     
        /**
         * @return the number of apps in the store
         */
        public int getNumberOfApps()
        {
            return appList.size();
        }
     
        /**
         * Removes all the apps from the store
         */
        public void clearAppStore()
        {
            appList.clear();
        }
     
        /**
         * Print all the apps in the store
         */
        public void printAppList()
        {
            System.out.println("============= " + appStoreName + " =============");
            if (appList.size() == 0) {
                System.out.println("No apps in the store");
            }
            else {
                for (App currentApp : appList) {
                    currentApp.printAppInfo();
                }
            }
            System.out.println("===========================================");
        }
     
        /**
         * Find an app by name
         * @param the name of the app being looked for
         * @return the name of the app if found
         */
        public App findApp(String name)
        {
            for(App app : appList) {
                if(app.getName().equals(name)) {
                    return app;
                }
            }
            return null;
        }
     
        /**
         * @remove an app from the App store
         * @param is name of app to remove
         */
        public App removeApp(String name)
        {
            App removeApp = null;
            for(App app : appList) {
                if(app.getName().equals(name)) {
                    appList.remove(app);
                    removeApp = app;
                    break;
                }
            }
            return removeApp;
        }    
     
        /**
         * Find apps by same author
         * @param is name of given author
         * @return list of apps by given author
         * If no apps by author, return empty list, not null
         * Do not print anything
         */
        public ArrayList<App> getAppsByAuthor(String name)
        {
            ArrayList<App> appsByAuthor = new ArrayList<App>();
            for(App app : appList) {
                if (app.getAuthor() != (name)) {
     
                }
     
                if (app.getAuthor().equals(name)) {
                    appsByAuthor.add(app);    
                }
            }
            return appsByAuthor;
     
        }
    }
     
    App Class
     
    /**
     * An app for a mobile device
     * 
     
     */
    public class App
    {
        private String name;
        private String author;
        private double price;
        private int rating; // valid ratings are 1-4 or 0 meaning not rated
     
        /**
         * Create an app with the given name, author, price, and rating
         * @param appName the app name
         * @param appAuthor the app author
         * @param appPrice the price of the app (0 if the app is free)
         * @param appRating the app's rating
         */
        public App(String appName, String appAuthor, double appPrice, int appRating)
        {
            name = appName;
            author = appAuthor;
            price = appPrice;
            rating = appRating;
        }    
     
        /**
         * Create an app with the given name, author, and price that is not rated
         * @param appName the app name
         * @param appAuthor the app author
         * @param appPrice the price of the app (0 if the app is free)
         */
        public App(String appName, String appAuthor, double appPrice)
        {
            name = appName;
            author = appAuthor;
            price = appPrice;        
        }
     
        /**
         * @return the app name
         */
        public String getName()
        {
            return name;
        }
     
        /**
         * @return the app author
         */
        public String getAuthor()
        {
            return author;
        }
     
        /**
         * @return the app price
         */
        public double getPrice()
        {
            return price;
        }
     
        /**
         * Set the price of this app to the value given
         * @param newPrice new price for this app
         */
        public void setPrice(double newPrice)
        {
            if (newPrice >= 0) {
                price = newPrice;
            }
            else {
                System.out.println("Error: Price must be greater than or equal to 0");
            }
        }
     
        /**
         * @return true if this app is free, false otherwise
         */
        public boolean isFree()
        {   
            if(price == 0) {
                return true;
            }
            else {
                return false;
            }
        }
     
        /**
         * @return the app rating
         */
        public int getRating()
        {
            return rating;
        }
     
        /**
         * Set the rating of this app to the value given
         * @param newRating new rating for this app
         * Valid rating is 1-4
         */
        public void setRating(int newRating)
        {
            if((newRating >= 1) && (newRating <= 4)) {
                rating = newRating;
            }
            else if((newRating == 0) || (newRating > 4)) {
                System.out.println("Error: Valid rating range is 1-4.");
            }
        }
     
        /**
         * Reset the rating of this app to not rated
         */
        public void resetRating()
        {
            rating = 0;
        }
     
        /**
         * Increase the rating of this app by 1
         */
        public void increaseRating()
        {
            if(rating >= 0 && rating <= 3) {
                rating = rating + 1;
            }
            else if(rating == 0 || rating >= 4) {
                rating = rating;
            }
        }
     
        /**
         * Decrease the rating of this app by 1
         */
        public void decreaseRating()
        {
            if(rating == 1) {
                rating = 1;
            }
            else if(rating >= 2 && rating <= 4){
                rating = rating - 1;
            }
            else if(rating == 0){
                 rating = rating;
            }
        }
     
        /**
         * Print information on this app
         */
        public void printAppInfo()
        {
            System.out.println("---------------------------------");
            System.out.println("App: " + name);
            System.out.println("Author: " + author);
            if(price == 0) {
                System.out.println("Price: FREE");
            }
            else{
            System.out.println("Price: $" + price);
            }
            if(rating == 0) {
                System.out.println("Rating: (not rated)");
            }
            else{
            System.out.println("Rating: " + rating);
            }
            System.out.println("---------------------------------");
        }
    }
    Last edited by misterCrypto; August 10th, 2021 at 12:37 PM.

  8. #33
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: ArrayList<> String searches and loops

    Where is the main method for starting the program's execution and calling methods to test them?

    How do you execute the code for testing?
    If you don't understand my answer, don't ignore it, ask a question.

  9. #34
    Member
    Join Date
    Jul 2021
    Posts
    40
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: ArrayList<> String searches and loops

    The main method is the first source code that I just posted. Below that one is the App Class. When I execute the code, I click compile, then I go to another window that shows two objects AppStore and App. Then I create a new object called either AppStore or App. When I do this, I'm then prompted to fill in fields in a dialogue box. So, if I click create new Object AppStore, the first thing it asks me is new AppStore name input String. When that is complete the object then posts to the object bar. From that object I can execute all of the methods in that Class.

  10. #35
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: ArrayList<> String searches and loops

    Sorry, I do not know how BlueJ works and can not help you with your problems in using it.

    The main method is the first source code that I just posted
    Are you sure there is a method named: main? I do not see it. Can you copy only the contents of the main method and paste it here?
    If you don't understand my answer, don't ignore it, ask a question.

  11. #36
    Member
    Join Date
    Jul 2021
    Posts
    40
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: ArrayList<> String searches and loops

    I understand. I look for help online a lot but no one uses BlueJ so it doesn't translate the same. So, there is no main method. You are right. When you execute this code, does it run?
    Last edited by misterCrypto; August 10th, 2021 at 12:35 PM.

  12. #37
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: ArrayList<> String searches and loops

    When you execute this code, does it run?
    It will not execute without a main method.

    Also the code in post#32 will not compile without errors.
    The comment started on line 4 is not closed with the ending */
    If you don't understand my answer, don't ignore it, ask a question.

  13. #38
    Member
    Join Date
    Jul 2021
    Posts
    40
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: ArrayList<> String searches and loops

    That sucks. I feel better about it now than I did an hour ago, so I'm happy for that. I fixed line 4. Not sure where the other errors are. I copied and pasted. Is there any way to upload screenshots? Also, can you help me with return emptyList? As I'm reading through the text, I just came across main method for the first time. Chapter 6.
    Last edited by misterCrypto; August 10th, 2021 at 01:03 PM.

  14. #39
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: ArrayList<> String searches and loops

    help me with return emptyList
    Why do you think the code does not return an empty list?
    When you test the code with an unknown author, what does the method return?
    If you don't understand my answer, don't ignore it, ask a question.

  15. #40
    Member
    Join Date
    Jul 2021
    Posts
    40
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: ArrayList<> String searches and loops

    Interesting point. I see in the book a isEmpty(), while I've been looking this up I see emptyList, so I guess I just assumed that it was a function. Ok. Can you tell me if this code is right for comparing strings that aren't alike, please? When I execute it, it's bringing up the dialogue box to try and show me the apps that are created by the given name, but there are none.

     
        /**
         * Find apps by same author
         * @param is name of given author
         * @return list of apps by given author
         * If no apps by author, return empty list, not null
         * Do not print anything
         */
        public ArrayList<App> getAppsByAuthor(String name)
        {
            ArrayList<App> appsByAuthor = new ArrayList<App>();
            for(App app : appList) {
                if (app.getAuthor() != (name)) {
                }
     
                if (app.getAuthor().equals(name)) {
                    appsByAuthor.add(app);    
                }
            }
            return appsByAuthor;
        }

  16. #41
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: ArrayList<> String searches and loops

    tell me if this code is right for comparing strings
    Yes, It uses the equals method which is the correct way to determine if two Strings are equal or not.
    Do not use == or != when testing the contents of objects like Strings.

    There is no need to have a separate test for not equal. Two Strings are either equal or not equal.
    With an if statement:
      if(some test that returns true or false) {
          // execute here if true
      }else {
         // execute here if false
      }
    If you don't understand my answer, don't ignore it, ask a question.

  17. #42
    Member
    Join Date
    Jul 2021
    Posts
    40
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: ArrayList<> String searches and loops

    Ultimately I came to that conclusion, but not soon enough. There's one more method that I'm really having trouble with. Are you up for helping? This is what it entails. Essentially they are asking me to create a method that "separates" the apps by their rating and returns the number of apps with the given rating. Valid ratings can only be 1-4.

    Write a method called getNumAppsWithRating that takes an int parameter representing a rating, and returns the number of apps in the app store that have the given rating.

    Example: If two apps in the store have rating 3, then the call getNumAppsWithRating(3) will return 2.

    I've been trying for a while now and I can't seem to compare get.appRating() with the parameter rating. Suggestions?

  18. #43
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: ArrayList<> String searches and loops

    compare get.appRating() with the parameter rating. Suggestions?
    Post the code and the error messages.
    If you don't understand my answer, don't ignore it, ask a question.

  19. #44
    Member
    Join Date
    Jul 2021
    Posts
    40
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: ArrayList<> String searches and loops

    I haven't been getting any error messages, it just hasn't been doing what I'm wanting it to do. Here's the code I tried originally, I've tried several things by now though.
     
    public ArrayList<App> getNumAppsWithRating(int rating)
    { 
        ArrayList<App> numAppsWithRating = new ArrayList<App>();
        int count = 0;
        for(App app : appList) {
            if(app.getRating() == (rating)) {
            count++;
            return numAppsWithRating;
                }  
            }
            return null;
     }

  20. #45
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: ArrayList<> String searches and loops

    it just hasn't been doing what I'm wanting it to do
    What is the method supposed to do?
    Please make a list of the steps the code needs to take to do what you want
    and post them here. Each item in the list should be a simple step.

    Note: The posted code does not have the comments that all the other posted code has.
    The comments before the methods describe what the method is supposed to do, what arguments it will receive and what value it will return.
    If you don't understand my answer, don't ignore it, ask a question.

  21. #46
    Member
    Join Date
    Jul 2021
    Posts
    40
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: ArrayList<> String searches and loops

    Ok, no problem. This project is an AppStore that sells Apps. I have two classes, AppStore and App. Each App that is entered into the store has a String Name (name of app), String name (name of author), double price, and integer rating.

    They are asking me to write a method called getNumAppsWithRating that takes an int parameter representing a rating, and returns the number of apps in the app store

    I need to return the number of apps with the given rating.

    Example: if two apps in the store have a rating of 3 then the call to getNumAppsWithRating(3) should return the number 2.

  22. #47
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: ArrayList<> String searches and loops

    write a method called getNumAppsWithRating that takes an int parameter representing a rating, and returns the number of apps in the app store
    Ok, what steps does the method need to take to do that?
    Make a list of the steps and post it.
    If you don't understand my answer, don't ignore it, ask a question.

  23. #48
    Member
    Join Date
    Jul 2021
    Posts
    40
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: ArrayList<> String searches and loops

    Got it, here's what I've been working on.
     
    public ArrayList<App> getNumAppsWithRating(int rating)
    { 
       ArrayList<App> numAppsWithRating = new ArrayList<App>();
       int count = 0;
       for(App app : appList) {
           if(app.getRating() == (rating)) {
           rating = rating;
           count++;
           return numAppsWithRating;
           }  
       }
       return null;
    }

    I used a for each loop because it has to run the entire collection. I'm not sure if I need the count, I felt like since I was looking for multiple occurrences I should count them and that would give me the NumAppsWithRating for the given rating. Also, the app rating can only be rated 1-4.

  24. #49
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: ArrayList<> String searches and loops

    Where is the list of steps the method is supposed to do? Don't write any code yet.
    You need to decide what the method is supposed to do BEFORE writing the code to do it.

    Where are the comments before the method that describe what it is supposed to do?
    For example:
        /**
         * Find an app by name
         * @param the name of the app being looked for
         * @return the name of the app if found
         */
    If you don't understand my answer, don't ignore it, ask a question.

  25. #50
    Member
    Join Date
    Jul 2021
    Posts
    40
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: ArrayList<> String searches and loops

    Sorry, I didn't include because earlier I missed curly bracket and messed your compiling up. Will include.

    /**
    *@locate apps that have been rated
    *@param represents a rating
    *return the number of apps in store that
    *have given rating
    *Example: If two apps have a rating of 3, then
    *the call to getNumAppsWithRating(3) returns 2
    */

    I need to find the apps that have been rated.

    I need to find out how many apps have the given rating.

    I need to return the number of apps that are in the store that have a particular rating.

    The parameter represents the rating we're looking for.

Page 2 of 3 FirstFirst 123 LastLast

Similar Threads

  1. HELP WITH FOR LOOPS! trying to concatenate without using string builder
    By janeeatsdonuts in forum What's Wrong With My Code?
    Replies: 3
    Last Post: February 24th, 2013, 09:00 AM
  2. Write a method that searches the BST for a given input
    By Jurgen in forum Algorithms & Recursion
    Replies: 4
    Last Post: January 6th, 2012, 11:46 AM
  3. Finding String in ArrayList
    By Noob_Programmer in forum What's Wrong With My Code?
    Replies: 3
    Last Post: August 6th, 2011, 05:18 AM
  4. private Map<String, ArrayList> xlist = new HashMap<String, ArrayList>();
    By Scotty in forum What's Wrong With My Code?
    Replies: 1
    Last Post: March 21st, 2011, 08:37 AM
  5. ArrayList to String/outOfBounds
    By Scotty in forum What's Wrong With My Code?
    Replies: 4
    Last Post: February 28th, 2011, 04:41 PM