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.

Results 1 to 20 of 20

Thread: method array list

  1. #1
    Member
    Join Date
    Sep 2013
    Posts
    35
    My Mood
    Goofy
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Default method array list

    i just want to make sure I did this correctly. Does it look right?
    /** a method returning an ArrayList of Books whose price is less than a given number
     * @param searchDouble
     * @return 
     */
    public ArrayList<Book> searchForPrice(double searchDouble)
    {
        ArrayList<Book> searchResult = new ArrayList<>();
        for(Book lessBook : library)
        {
            if((lessBook.getTitle()).indexOf((int) searchDouble)!=-1)
                searchResult.add(lessBook);
        }
        searchResult.trimToSize();
        return searchResult;
        }
    }

    The rest of my code for the array List:
    public class BookStore 
    {
    private ArrayList<Book> library;
     
    /**default constructor
     * instantiates ArrayList of Books
     */
    public BookStore()
    {
        library=new ArrayList<>();
        library.add(new Book("Intro to Java", "James", 56.99));
        library.add(new Book("Advanced Java", "Green", 65.99));
        library.add(new Book("Java Servlets", "Brown", 75.99));
        library.add(new Book("Intro to HTML", "James", 29.49));
        library.add(new Book("Intro to Flash", "James", 34.99));
        library.add(new Book("Advanced HTML", "Green", 56.99));
        library.trimToSize();
    }
     
    /** toString
     * @return each book in library, one per line
     */
    @Override
    public String toString()
    {
        String result = "";
        for(Book tempBook : library)
        {
            result += tempBook.toString()+"\n";
        }
        return result;
    }


  2. #2
    Member llowe29's Avatar
    Join Date
    Jul 2013
    Posts
    116
    My Mood
    Tired
    Thanks
    9
    Thanked 5 Times in 5 Posts

    Default Re: method array list

    yes now create a tester class so you can see for yourself

  3. The Following User Says Thank You to llowe29 For This Useful Post:

    nepperso (December 7th, 2013)

  4. #3
    Member
    Join Date
    Sep 2013
    Posts
    35
    My Mood
    Goofy
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Default Re: method array list

    Actually - wait ? i think it should be this?
    public ArrayList<Book> searchForPrice(String searchString)
    {
        ArrayList<Book> searchResult = new ArrayList<>();
        //converts search string to double
        double maxPrice = Double.parseDouble(searchString);
        for(Book lessBook : library)
        {
            //If itemPrice < maxPrice, add it to the list
            if(lessBook.getPrice()< maxPrice)
                searchResult.add(lessBook);
        }
        searchResult.trimToSize();
        return searchResult;
        }

  5. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: method array list

    You will find it recommended to abstract the details of the implementation by using the following approach:
    // declaration
    List<Book> library;
     
    // initialization
    library = new ArrayList<Book>();

  6. The Following User Says Thank You to GregBrannon For This Useful Post:

    nepperso (December 7th, 2013)

  7. #5
    Member
    Join Date
    Sep 2013
    Posts
    35
    My Mood
    Goofy
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Default Re: method array list

    Quote Originally Posted by GregBrannon View Post
    You will find it recommended to abstract the details of the implementation by using the following approach:
    // declaration
    List<Book> library;
     
    // initialization
    library = new ArrayList<Book>();
    So instead of saying
    private ArrayList<Book> library;
    write it as
    private List<Book> library; 
    library = new ArrayList<Book>();

  8. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: method array list

    Yes, or it can all be done in one line (but I'd normally initialize in the constructor):

    private List<Book> library = new ArrayList<Book>();

  9. #7
    Member
    Join Date
    Sep 2013
    Posts
    35
    My Mood
    Goofy
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Default Re: method array list

    when i change that it causes the arralist trimtosize to give an error:
       library.trimToSize();
    }
    says can't find it

    --- Update ---

    what would be better to use do you think?
    /** a method returning an ArrayList of Books whose price is less than a given number
     * @param searchDouble
     * @return 
     */
    public ArrayList<Book> searchForPrice(double searchDouble)
    {
        ArrayList<Book> searchResult = new ArrayList<>();
        for(Book lessBook : library)
        {
            if((lessBook.getTitle()).indexOf((int) searchDouble)!=-1)
                searchResult.add(lessBook);
        }
        searchResult.trimToSize();
        return searchResult;
        }

    or better to use:
    public ArrayList<Book> searchForPrice(String searchString)
    {
        ArrayList<Book> searchResult = new ArrayList<>();
        //converts search string to double
        double maxPrice = Double.parseDouble(searchString);
        for(Book lessBook : library)
        {
            //If itemPrice < maxPrice, add it to the list
            if(lessBook.getPrice()< maxPrice)
                searchResult.add(lessBook);
        }
        searchResult.trimToSize();
        return searchResult;
        }

  10. #8
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: method array list

    You're right. To use methods specific to ArrayList, those not included in List, will require casting library to an ArrayList. A bit of a pain. Which should you use? Whichever you prefer. Sometimes you just gotta step around the experts while they shake their fingers at you and get on with the job.

  11. #9
    Member
    Join Date
    Sep 2013
    Posts
    35
    My Mood
    Goofy
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Default Re: method array list

    lol. I'm just copying what was written in the book, than doing what the question says i'm to do.

    • a method returning the book with the lowest price in the library
    • a method searching the library for Books of a given author and returning an ArrayList of such Books
    • a method returning an ArrayList of Books whose price is less than a given number

    So for the part that says:
    • a method returning an ArrayList of Books whose price is less than a given number
    I took the method that the book wrote for title Search which was
    public ArrayList<Book> searchForTitle(String searchString)
    {
        ArrayList<Book> searchResult = new ArrayList<>();
        for(Book currentBook : library)
        {
            if((currentBook.getTitle()).indexOf(searchString)!=-1)
                searchResult.add(currentBook);
        }
        searchResult.trimToSize();
        return searchResult;
        }

    and modified it for the getPrice()?
    /** a method returning an ArrayList of Books whose price is less than a given number
     * @param searchDouble
     * @return 
     */
    public ArrayList<Book> searchForPrice(double searchDouble)
    {
        ArrayList<Book> searchResult = new ArrayList<>();
        for(Book lessBook : library)
        {
            if((lessBook.getTitle()).indexOf((int) searchDouble)!=-1)
                searchResult.add(lessBook);
        }
        searchResult.trimToSize();
        return searchResult;
        }
    But than i thought will that really return me the lower amount?

    so thought this might work better:
    public ArrayList<Book> searchForPrice(String searchString)
    {
        ArrayList<Book> searchResult = new ArrayList<>();
        //converts search string to double
        double maxPrice = Double.parseDouble(searchString);
        for(Book lessBook : library)
        {
            //If itemPrice < maxPrice, add it to the list
            if(lessBook.getPrice()< maxPrice)
                searchResult.add(lessBook);
        }
        searchResult.trimToSize();
        return searchResult;
        }
    Last edited by nepperso; December 7th, 2013 at 01:41 PM. Reason: additional comments

  12. #10
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: method array list

    Your second attempt seems correct to me, though I'm not sure why the method doesn't expect a double parameter for the max book price. Does it work?

  13. The Following User Says Thank You to GregBrannon For This Useful Post:

    nepperso (December 7th, 2013)

  14. #11
    Member
    Join Date
    Sep 2013
    Posts
    35
    My Mood
    Goofy
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Default Re: method array list

    i figured double cause that's what i have for the price in the class:
    package natashaepperson_chapter_09_exercise_94;
     
    public class Book {
    private String title;
    private String author;
    private double price;
     
    /**default constructor
     */
    public Book()
    {
        title = "";
        author = "";
        price = 0.0;
    }
     
    /** overloaded constructor
     * @param newTitle the value to assign to title
     * @param newauthor the value to assign to author
     * @param newPrice the value to assign to price
     */
    public Book(String newTitle, String newAuthor, double newPrice)
    {
        title = newTitle;
        author = newAuthor;
        price = newPrice;
    }
     
    /** getTitle method
     * @return the title
     */
    public String getTitle()
    {
        return title;
    }
     
    /** getAuthhor method
     * @return the author
     */
    public String getAuthor()
    {
        return author;
    }
     
    /**getPrice method
     * @return the price
     */
    public double getPrice()
    {
        return price;
        }
     
    /** toString
     * @return title, author, and price
     */
    @Override
    public String toString()
    {
        return ("title: "+title+"\t"
                +"author: "+author+"\t"
                +"price: "+price);
        }
    }

  15. #12
    Member
    Join Date
    Sep 2013
    Posts
    35
    My Mood
    Goofy
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Default Re: method array list

    Okay now I am trying to do the client test for it.
    I have
    public static void main(String[]args)
    {
        BookStore bs = new BookStore();
     
        String keyword = JOptionPane.showInputDialog(null,
                "Enter a keyword ");
        System.out.println("Our book collection is: ");
        System.out.println(bs.toString());
     
        ArrayList<Book> results = bs.searchForTitle(keyword);
     
        System.out.println("The search results for "+keyword
                +" are: ");
        for(Book tempBook : results)
            System.out.println(tempBook.toString());
     
        /*Enter Price of Book
         * returns books lower than price entered
         */
        String Price = JOptionPane.showInputDialog(null,
                "Enter a Price ");
        ArrayList<Book> results = bs.searchForPrice(keyword);
        System.out.println("The search results for "+Price
                +" are: ");
        for(Book tempBook : results)
            System.out.println(tempBook.toString());
    }
    }

    It's saying this part: ArrayList<Book> results = bs.searchForPrice(keyword);
    is already defined in teh array above. But not sure how else to set it up so that it will search for price instead of searching teh same array?

  16. #13
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: method array list

    Remove this: "ArrayList<Book>" from that line. You don't re-declare results, just change its value(s).

  17. #14
    Member
    Join Date
    Sep 2013
    Posts
    35
    My Mood
    Goofy
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Default Re: method array list

    so if i fix it to
        String Price = JOptionPane.showInputDialog(null,
                "Enter a Price ");
     
        System.out.println("The search results for "+Price
                +" are: ");
        for(Book tempBook : results)
            System.out.println(tempBook.toString());

    it's not calling the searchForPrice array in the class.
    While it will give me a 2nd dialog it just repeats the same result as before eve though i put in say 30.00 and it should return any book under that amount

  18. #15
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: method array list

    Where do you try to call searchForPrice()?

    I would think the code you posted might look like:
    String Price = JOptionPane.showInputDialog(null,
            "Enter a Price ");
     
    results = searchForPrice( Price );  // Price should be price
     
    System.out.println("The search results for "+Price
            +" are: ");
    for(Book tempBook : results)
        System.out.println(tempBook.toString());

  19. The Following User Says Thank You to GregBrannon For This Useful Post:

    nepperso (December 7th, 2013)

  20. #16
    Member
    Join Date
    Sep 2013
    Posts
    35
    My Mood
    Goofy
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Default Re: method array list

    ahh so take out the arraylist comment since i already have it but keep the results and make it price!

    though i had to add in the bs. for it to work- works correctly now too! YAY!!!
    String Price = JOptionPane.showInputDialog(null,
                "Enter a Price ");
    results = bs.searchForPrice(Price);  // Price should be price
     
    System.out.println("The search results for "+Price
            +" are: ");
    for(Book tempBook : results)
        System.out.println(tempBook.toString());

    Now i gotta do the rest of the problem lmao
    • a method returning the book with the lowest price in the library
    • a method searching the library for Books of a given author and returning an ArrayList of such Books

  21. #17
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: method array list

    Great! Glad it worked, and good job figuring out the bs. part. I wasn't sure what object the method was being called on, and I forgot to mention it.

  22. The Following User Says Thank You to GregBrannon For This Useful Post:

    nepperso (December 8th, 2013)

  23. #18
    Member
    Join Date
    Sep 2013
    Posts
    35
    My Mood
    Goofy
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Default Re: method array list

    so my 3 problems for the assignment were:
    • a method returning the book with the lowest price in the library
    • a method searching the library for Books of a given author and returning an ArrayList of such Books
    • a method returning an ArrayList of Books whose price is less than a given number

    I did 2 and 3. I'm not sure how to tackle 1 BECAUSE of 2 and 3. i have jpanel pops for the other two and the resolve correctly. I'm not sure what is the best way to do "return the book with the lowest price in the library" that won't mess up the other 2?

    This is what I have so far and it all works correctly:
    /*
    94. Modify the Book Store and Book Search Engine classes from the chapter.
    You should include the following additional methods and test them:
    • a method returning the book with the lowest price in the library
    • a method searching the library for Books of a given author and returning an ArrayList of such Books
    • a method returning an ArrayList of Books whose price is less than a given number
    Natasha Epperson
     */
    package natashaepperson_chapter_09_exercise_94;
     
    public class Book {
    private String title;
    private String author;
    private double price;
     
    /**default constructor
     */
    public Book()
    {
        title = "";
        author = "";
        price = 0.0;
    }
     
    /** overloaded constructor
     * @param newTitle the value to assign to title
     * @param newauthor the value to assign to author
     * @param newPrice the value to assign to price
     */
    public Book(String newTitle, String newAuthor, double newPrice)
    {
        title = newTitle;
        author = newAuthor;
        price = newPrice;
    }
     
    /** getTitle method
     * @return the title
     */
    public String getTitle()
    {
        return title;
    }
     
    /** getAuthhor method
     * @return the author
     */
    public String getAuthor()
    {
        return author;
    }
     
    /**getPrice method
     * @return the price
     */
    public double getPrice()
    {
        return price;
        }
     
    /** toString
     * @return title, author, and price
     */
    @Override
    public String toString()
    {
        return ("title: "+title+"\t"
                +"author: "+author+"\t"
                +"price: "+price);
        }
    }
    and for the search engine:
    /*
     * BookSearchEngine class
     */
    package natashaepperson_chapter_09_exercise_94;
    import java.util.ArrayList;
    import javax.swing.JOptionPane;
     
    public class BookSearchEngine 
    {
    public static void main(String[]args)
    {
        BookStore bs = new BookStore();
     
        String keyword = JOptionPane.showInputDialog(null,
                "Enter a keyword ");
        System.out.println("Our book collection is: ");
        System.out.println(bs.toString());
     
        ArrayList<Book> results = bs.searchForTitle(keyword);
     
        System.out.println("The search results for "+keyword
                +" are: ");
        for(Book tempBook : results)
            System.out.println(tempBook.toString());
    /*Enter Author of book
     * searchs and returns Author of book
     */
    String Author = JOptionPane.showInputDialog(null,
            "Enter Author ");
    results = bs.searchforAuthor(Author);//Authors name
     
    System.out.println("The search results for "+Author
            +" are: ");
    for(Book tempBook : results)
        System.out.println(tempBook.toString());
     
    /*Enter Price of Book
    * returns books lower than price entered
    */
    String Price = JOptionPane.showInputDialog(null,
                "Enter a Price ");
    results = bs.searchForPrice(Price);  // Price should be price
     
    System.out.println("The search results for "+Price
            +" are: ");
    for(Book tempBook : results)
        System.out.println(tempBook.toString());
     
    }
    }
    for the class
    /*
     * BookStore Class
     */
    package natashaepperson_chapter_09_exercise_94;
     
    import java.util.ArrayList;
     
    public class BookStore 
    {
    private ArrayList<Book> library;
     
    /**default constructor
     * instantiates ArrayList of Books
     */
    public BookStore()
    {
        library=new ArrayList<>();
        library.add(new Book("Intro to Java", "James", 56.99));
        library.add(new Book("Advanced Java", "Green", 65.99));
        library.add(new Book("Java Servlets", "Brown", 75.99));
        library.add(new Book("Intro to HTML", "James", 29.49));
        library.add(new Book("Intro to Flash", "James", 34.99));
        library.add(new Book("Advanced HTML", "Green", 56.99));
        library.trimToSize();
    }
     
    /** toString
     * @return each book in library, one per line
     */
    @Override
    public String toString()
    {
        String result = "";
        for(Book tempBook : library)
        {
            result += tempBook.toString()+"\n";
        }
        return result;
    }
     
    /** Generates list of books containing searchString
     * @param searchString the keyword to search for
     * @return the ArrayList of books containing the keyword
     */
    public ArrayList<Book> searchForTitle(String searchString)
    {
        ArrayList<Book> searchResult = new ArrayList<>();
        for(Book currentBook : library)
        {
            if((currentBook.getTitle()).indexOf(searchString)!=-1)
                searchResult.add(currentBook);
        }
        searchResult.trimToSize();
        return searchResult;
        }
    /** a method returning an ArrayList of Books whose price is less than a given number
     * @param searchDouble
     * @return 
     */
    public ArrayList<Book> searchForPrice(String searchString)
    {
        ArrayList<Book> searchResult = new ArrayList<>();
        //converts search string to double
        double maxPrice = Double.parseDouble(searchString);
        for(Book lessBook : library)
        {
            //If itemPrice < maxPrice, add it to the list
            if(lessBook.getPrice()< maxPrice)
                searchResult.add(lessBook);
        }
        searchResult.trimToSize();
        return searchResult;
        }
    public ArrayList<Book> searchforAuthor(String searchString)
    {
        ArrayList<Book> searchResult = new ArrayList<>();
        for(Book thisAuthor : library)
        {
            if((thisAuthor.getAuthor()).indexOf(searchString)!=-1)
                searchResult.add(thisAuthor);
        }
        searchResult.trimToSize();
        return searchResult;
        }
    }

  24. #19
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: method array list

    I'm not sure how to tackle 1 BECAUSE of 2 and 3.
    I think you mean you're unable to transition from the pattern of asking for data, responding with results. So for Problem 1, there is no input required. The program simply outputs the book with the lowest price. Create a method to find it, return it, and print it out.

    Why does your program use JOptionPane methods to get data but uses the console to output the data? Why not use JOptionPane methods to present the data?[COLOR="Silver"]

  25. The Following User Says Thank You to GregBrannon For This Useful Post:

    nepperso (December 9th, 2013)

  26. #20
    Member
    Join Date
    Sep 2013
    Posts
    35
    My Mood
    Goofy
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Default Re: method array list

    i'm not sure. I was only following what the book did for the coding.
    hrm okay I see what you mean.

    This is the first java class I've ever taken and the last lol. It's a strange requirement for my mathematics degree. It's built into the core requirement for all science based degrees at my university. I am enjoying and wouldn't mind learning more programming but my plate is full to begin with lol

Similar Threads

  1. Return a List from a method
    By iHank in forum What's Wrong With My Code?
    Replies: 3
    Last Post: October 30th, 2013, 09:14 AM
  2. Converting Two dimensional array into an Array list
    By NewbieJavaProgrammer in forum Object Oriented Programming
    Replies: 11
    Last Post: September 29th, 2012, 04:23 PM
  3. help with delete method of linked list
    By sonicjr in forum Collections and Generics
    Replies: 1
    Last Post: February 18th, 2012, 09:21 PM
  4. Array List of Array Lists working for first item but not for second.
    By javapenguin in forum Collections and Generics
    Replies: 6
    Last Post: February 15th, 2012, 05:12 PM
  5. override list add method?
    By ober0330 in forum Collections and Generics
    Replies: 10
    Last Post: July 17th, 2011, 07:34 PM