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 11 of 11

Thread: How to search through values of Array?

  1. #1
    Member
    Join Date
    Jan 2014
    Posts
    30
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default How to search through values of Array?

    Hello everyone, I am java noob so please bear with me, I have two classes for a program thats supposed to search for books but I am currently stuck!. Where I am stuck is at the bottom of the BookSearch class, and I am trying to essentially only search my array for the price and title, but, in my book class I declared the attributes of the book to have 3 parameters (see below). So the little tiny thing that I can't figure out is that if I want to compare 2 values given to me by the user (a title and a price) then I only want to compare those 2 parameters, but I have no idea how to go about it since my Book class has 3 parameters, so essentially I am asking how do I check through an array with 3 parameters but only want to check 2 of them for the entire array. I tried if bkArr[i].equals(pric) && bkArr[i].equals(titl) ... but it didn't work and I know it wouldn't work, it just dosen't look good. I am completely baffled by this and have spent 3 hours just staring at my screen trying to figure something which I think should be very easy to do. If anyone dosen't understand what I am trying to do please ask and Il try to explain again, thanks in advance !

    class Book {
    	//Attributes of Book
     
    	private String title;
    	private long ISBN;
    	private double price;
     
    	//Constructor of Book
     
    	public Book()
    	{
    		System.out.println("Creating Book.....");
    		title = "abc";
    		price = 25;
    		ISBN = 1234;
    	}
     
    	public Book(String ti, long ib, double pr)
    	{
    		title = ti;
    		price = pr;
    		ISBN = ib;
    	}
    	//Methods of book
     
    	public Book(Book bk)
    	{ //Copy Constructor
    		System.out.println("Creating object with copy constructor.....");
    		title = bk.title;
    		price = bk.price;
    		ISBN = bk.ISBN;
    	}
     
    	public void setPrice(double pr)
    	{//sets the price of the book
    		price = pr;
    	}
    	public double getPrice()
    	{//gets the price of the book
    		return price;
    	}
     
    	public void setTitle(String ti)
    	{//sets the title of the book
    		title = ti;
    	}
     
    	public String getTitle()
    	{//gets the title of the book
    		return title;
    	}
     
    	public void setISBN(long num)
    	{//sets the ISBN of the book
    		ISBN = num;
    	}
     
    	public long getISBN()
    	{//gets the ISBN of the book
    		return ISBN;
    	}
     
    	public String toString()
    	{//returns book values
    		System.out.println("The book title is " + title + ", the ISBN number is " + ISBN + " and the price is " + price +"$.\n\n");
    		return (title + " " + ISBN + " " + price);
    	}
    }

    import java.util.Scanner;
    public class BookSearch 
    {
    	public static void main (String[] args) 
    	{
    		String titl, yn;  
    		int i, pric;
    	//Create 10 books with the array
    		Book[] bkArr = new Book[10];
     
    	//Create 10 book objects with values
    	    Book b1 = new Book ("hi",10, 1001);
    	    Book b2 = new Book ("hi",45, 1002);
    	    Book b3 = new Book ("hi",50, 1003);
    	    Book b4 = new Book ("hi",100, 1004);
    	    Book b5 = new Book ("hi",75, 1005);
    	    Book b6 = new Book ("hi",65, 1006);
    	    Book b7 = new Book ("hi",40, 1007);
    	    Book b8 = new Book ("hi",10, 1008);
    	    Book b9 = new Book ("hi",10, 1009);
    	    Book b10 = new Book ("hi",100,1010);
     
    	    bkArr[0] = b1;
    	    bkArr[1] = b2;
    	    bkArr[2] = b3;
    	    bkArr[3] = b4;
    	    bkArr[4] = b5;
    	    bkArr[5] = b6;
    	    bkArr[6] = b7;
    	    bkArr[7] = b8;
    	    bkArr[8] = b9;
    	    bkArr[9] = b10;
     
    	    Scanner kb = new Scanner(System.in);
    	    System.out.println("Please enter a book title, a price and either 'Yes' or 'No' for a combined search");
     
    	    titl = kb.next();
    	    pric = kb.nextInt();
    	    yn = kb.next();
     
    	    if (yn.equals("yes"))
    	    {
    	    	for (i = 0; i < bkArr.length; i++)
    	    	{
    	    		if (bkArr[i].
    	    	}
    	    }
     
    	    if (yn.equals("No"))
    	    {
     
    	    }
    	}
    }


  2. #2
    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: How to search through values of Array?

    Your construction of the array that contains Book objects can be improved:

    Book[] books = new Book[10];

    Then to populate the array with Book objects, use a for loop:
    for ( int i = 0 ; i < books.length ; i++ )
    {
        // create an argument for the constructor from the b1 - b10 code above
        books[i] = new Book( bookArgument );
    }
    Then to search the array:
    for ( Book book : books )
    {
        if ( book.getAttribute() == whatever )
        {
            // the item is found
        }
    }

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

    paco (April 11th, 2014)

  4. #3
    Member
    Join Date
    Jan 2014
    Posts
    30
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: How to search through values of Array?

    Hi there greg, I can't use the for loop because I have to declare my 10 books to be uniquely different from another ( i simply just put hi for the values of name for now), essentially 10 different books. And for your second piece of code I am not quite sure I understand what you are doing or trying to say. Are you trying to say make a method that getPriceandTitle from user, and then if it equals the book value etc. But I dont know how to do the == whatever part, sure I can make the method but where I am stuck is equating the method to make it equal to only 2 out of the 3 parameters of the book. Sorry if I am annoying, just greatly confused.

    what I am trying to do:
    if (yn.equals("yes")) //if the user enters yes, search for title and price
    	    {
    	    	for (i = 0; i < bkArr.length; i++)
    	    	{
    	    		//if  the values of bkArr[i] match only the price and title that the user has given, then display that title and book price.
    	    	}
    	    }

  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: How to search through values of Array?

    I can't use the for loop because I have to declare my 10 books to be uniquely different from another
    Of course you can do that using a for loop (or some kind of loop). You just need to be a bit more clever. Store the data that defines each book and apply it to an appropriate constructor to create each book during each pass through the loop.
    I dont know how to do the == whatever
    Do what you can or what you think you need to do to accomplish your task and post that, errors and all, so that we can see what you mean.

    You're not annoying.

    Explain what "equating the method to make it equal to only 2 out of the 3 parameters" means or is supposed to do. Give an example of a book, the user's search, and possible results from the desired method.

  6. #5
    Member
    Join Date
    Jan 2014
    Posts
    30
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: How to search through values of Array?

    Ok I dont understand how you can use the for loop to store the data for each book. If I use a loop won't they all be named the same and have the same parameters, if there is a way to avoid this I have no clue how to doit? I really am not sure how to do that code that you are talking about. What I meant about the parameters is in my class Book.java I created 3 constructors (I think thats what you call it) those being title, price and ISBN. Now in my booksearch.java im trying to do a loop that will check only title and price not ISBN as well. So in a for loop i will have an if statement going through each book checking to see if both the title and price match. I think I may have some problems in my book class or I am missing a method to do what I am trying to do. I am really lost still.

     
    if bkArr[i].Book(price,title) = Book(pric,title)
    System.out.println(+title + pric)
     
    //this is how i would express what I wanted to do but its wrong, not sure how to fix it
    Last edited by paco; April 7th, 2014 at 10:54 PM.

  7. #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: How to search through values of Array?

    Using a for loop to create the 10 books. Here's one way:
    import java.util.Scanner;
     
    public class BookSearch 
    {
            //Create 10 book objects with values
        private static String[] bookData =
                            { ( "hi  10 1001" ),
                              ( "hi  45 1002" ),
                              ( "hi  50 1003" ),
                              ( "hi 100 1004" ),
                              ( "hi  75 1005" ),
                              ( "hi  65 1006" ),
                              ( "hi  40 1007" ),
                              ( "hi  10 1008" ),
                              ( "hi  10 1009" ),
                              ( "hi 100 1010" ) };
     
        public static void main (String[] args) 
        {
            String titl, yn;  
            int i, pric;
            Book[] bkArr = new Book[10];
     
            // Create 10 books with the String[] bookData
            // (should be a separate method)
            for ( int j = 0 ; j < bookData.length ; j++ )
            {
                Scanner scan = new Scanner( bookData[j] );
                String title = scan.next();
                double price = scan.nextDouble();
                long isbn = scan.nextLong();
     
                bkArr[j] = new Book( title, isbn, price );
     
                // show the results after each book is created
                System.out.print( "Book " + j + " = " + bkArr[j] );
            }
     
            // etc . . . .
    And a similar way can be done with a single bookData String and a single scan object. I'm not sure which I prefer. And there are certainly other ways possible for those even more clever . . .

    Returning to your original question, (roughly) "How to search an array for two out of 3 attributes or class properties?"

    Keep in mind that the Book class has methods (getters or accessor methods) that return the attributes for the current book object, so the method that compares the results from different Book objects will reside outside the Book class. Also, more than one result is possible, so there must be a way to return multiple results. One way to accomplish the task would be with a method that looks something like:
    private boolean[] findBookMatches( Book[] books, String title, double price )
    {
        // create a boolean array to store the results
     
        // test each book in the books[] array to determine if it has
        // the title 'title' AND the price 'price'. set the corresponding
        // element in the boolean array true for each match found,
        // false for each book that doesn't match.
     
        // return the resulting boolean array
     
    } // end method findBookMatches()
    Hope this helps.

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

    paco (April 10th, 2014)

  9. #7
    Member
    Join Date
    Jan 2014
    Posts
    30
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: How to search through values of Array?

    Hey thanks for your help and patience, but unfortunately I still do not understand what you doing. It seems like your first piece of code is trying to just go through the book list and display the content of each and every book.I simply want to check the books- I think maybe perhaps I need to make a method like checkIfBooksAreEven(), but once again, I am baffled of about how to go about this, I would like to give you more examples of my attempts but I am kind of giving up since I have other things to attend to! But hey I am still trying to do this, so maybe in the method it can do something like a nested for loop checking the price and title and then if its matched it will return true, and on my book search class I can do something like if checkIfBooksAreEven = true then display book[i] etc.

    for your code Il put some comments to maybe show what I mean

     
     
     public static void main (String[] args) 
        {
            String titl, yn;  
            int i, pric;
            Book[] bkArr = new Book[10];
     
            // Create 10 books with the String[] bookData
            // (should be a separate method)
            for ( int j = 0 ; j < bookData.length ; j++ )
            {
                Scanner scan = new Scanner( bookData[j] );
                String title = scan.next();
                double price = scan.nextDouble();
                //long isbn = scan.nextLong(); dont need ISBN just price and title (because the user dosent know The isbn numbers and I am not asking for them
     
                bkArr[j] = new Book( title, isbn, price );
     
                // show the results after each book is created 
               // I dont want to display all the books, just the matching ones     ...  System.out.print( "Book " + j + " = " + bkArr[j] );
            }

    //in the book search class
     
    public Book compareBooks() // dont know how to go about writing this not sure if its right?
     
    If book[i] = book[scanner info that the user inputted]
     
    return true
    else false
     
    if true display the information

  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: How to search through values of Array?

    Your question:
    Now in my booksearch.java im trying to do a loop that will check only title and price not ISBN as well. So in a for loop i will have an if statement going through each book checking to see if both the title and price match.
    Focusing on your question, the desired method would look something like:

    private boolean[] findBookMatches( Book[] books, String title, double price )
    {
        // create a boolean array to store the results
     
        // test each book in the books[] array to determine if it has
        // the title 'title' AND the price 'price'. set the corresponding
        // element in the boolean array true for each match found,
        // false for each book that doesn't match.
        for ( int i = 0 ; i < books.length ; i++ )
        {
            if ( books[i].getTitle().equals( title ) && book[i].getPrice == price )
            {
                // a match has been found, so set the corresponding boolean array
                // element to true
                bookMatchArray[i] = true;
            }
        }
        // return the resulting boolean array
     
    } // end method findBookMatches()

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

    paco (April 10th, 2014)

  12. #9
    Member
    Join Date
    Jan 2014
    Posts
    30
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: How to search through values of Array?

    hi greg before I just saw your code I got something similar to yours, but it excludes making a method and it turns out it is not working, but the part of code that I got is pretty much identical to what you just told me...I re-arranged my code to look something like this (but its not working when I put in values and nothing comes back when I want it to display it):

    Scanner kb = new Scanner(System.in);
     
    	    System.out.println("Please enter a book title");
    	    titl = kb.next();
     
    	    System.out.println("Please enter a book price");
    	    pric = kb.nextDouble();
     
    	    System.out.println("Please enter yes or no for a combined search");
    	    yn = kb.next();
     
    	    if (yn.equals("yes"))
    	    {
    	    	for (i = 0; i < bkArr.length; i++)
    	    	{
    	    		if (bkArr[i].getTitle().equals(titl) && bkArr[i].getPrice() == pric)
    	    				{
    	    				System.out.println("Title Matched For:"+ titl);
    	    				System.out.printf("Price Matched For"+ pric);
    	    				}
    	    	}
    	    }

    essentially this was the code I was looking for all along: if (bkArr[i].getTitle().equals(titl) && bkArr[i].getPrice() == pric)
    If I do it your way and make a boolean method, then after bookMatchArray[i] = true; how would I display it? And also how would I implement the user info into the method on the other class, if the user is giving me info in my booksearch class and your method is in my book class how would the information transfer over? But to be honest I don't see why my code isn't working and why I need a method, my code runs through the for loop check if the price and title is equal and then should display when they are equal, I did some test runs and no go...Thanks again for your time.
    Last edited by paco; April 10th, 2014 at 11:45 AM.

  13. #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: How to search through values of Array?

    It's really helpful - almost necessary - to post executable code or error messages when you want help with code that "doesn't work." For example, here's runnable code using your own code that shows what you posted DOES work. Why it doesn't work for you is a mystery, BECAUSE you don't post a runnable example with a sample run.
    import java.util.Scanner;
     
    public class BookSearch3
    {
        //Create 10 book objects with values
        private static String[] bookData =
          { ( "hi0  10 1001" ),
            ( "hi1  45 1002" ),
            ( "hi2  50 1003" ),
            ( "hi3 100 1004" ),
            ( "hi4  75 1005" ),
            ( "hi5  65 1006" ),
            ( "hi6  40 1007" ),
            ( "hi7  10 1008" ),
            ( "hi8  10 1009" ),
            ( "hi9 100 1010" ) };
     
        public static void main (String[] args) 
        {
            String titl, yn;  
            int i;
            double pric;
     
            Book[] bkArr = new Book[10];
     
            // a Scanner object for user input
            Scanner kb = new Scanner(System.in);
     
            // Create 10 books with the String[] bookData
            // (should be a separate method)
            for ( int j = 0 ; j < bookData.length ; j++ )
            {
                Scanner scan = new Scanner( bookData[j] );
                String title = scan.next();
                double price = scan.nextDouble();
                long isbn = scan.nextLong();
     
                bkArr[j] = new Book( title, isbn, price );
     
                // show the results after each book is created
                System.out.print( "Book " + j + " = " + bkArr[j] );
            }
     
            System.out.println("Please enter a book title");
            titl = kb.next();
     
            System.out.println("Please enter a book price");
            pric = kb.nextDouble();
     
            System.out.println("Please enter yes or no for a combined search");
            yn = kb.next();
     
            if (yn.equals("yes"))
            {
                for (i = 0; i < bkArr.length; i++)
                {
                    if (bkArr[i].getTitle().equals(titl) && bkArr[i].getPrice() == pric)
                    {
                        System.out.println("Title Matched For:"+ titl);
                        System.out.printf("Price Matched For"+ pric);
                        System.out.println( "At index: " + i );
                    }
                }
            }
     
        } // end method main()
     
    }// end class BookSearch

  14. #11
    Member
    Join Date
    Jan 2014
    Posts
    30
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: How to search through values of Array?

    can you please explain this piece of code to me and the use for it? I am trying to understand it why the scanner is being used and what bookData is doing. thanks

     // Create 10 books with the String[] bookData
            for ( int j = 0 ; j < bookData.length ; j++ )
            {
                Scanner scan = new Scanner( bookData[j] );
                String title = scan.next();
                double price = scan.nextDouble();
                long isbn = scan.nextLong();
     
                bkArr[j] = new Book( title, isbn, price );
            }

    also I am trying to name my books by full name and Cant modify the array with more than 1 word

    { ( "harry potter  10 1" ),
            ( "hi1  45 2" ),
            ( "hi2  50 3" ),
            ( "hi3 100 4" ),
            ( "hi4  75 5" ),
            ( "hi5  65 6" ),
            ( "hi6  40 7" ),
            ( "hi7  10 8" ),
            ( "hi8  10 9" ),
            ( "hi9 100 10" ) };

    it gives me an error:

    Exception in thread "main" java.util.InputMismatchException
    	at java.util.Scanner.throwFor(Scanner.java:840)
    	at java.util.Scanner.next(Scanner.java:1461)
    	at java.util.Scanner.nextDouble(Scanner.java:2387)
    	at BookSearch.main(BookSearch.java:35)
    Last edited by paco; April 11th, 2014 at 09:15 PM.

Similar Threads

  1. how to find 2nd largest array if array values like{10,20,92,81,92,34}
    By anjijava16 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: November 2nd, 2013, 04:59 PM
  2. Linear Search in an array
    By camaleonx13 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: October 1st, 2013, 01:42 PM
  3. Search for the Array
    By Lurie1 in forum Collections and Generics
    Replies: 14
    Last Post: February 18th, 2012, 12:45 PM
  4. Array Search Method
    By Kyuubi426 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: June 28th, 2011, 08:31 PM
  5. Search for min and max values as columns position in array
    By susieferrari in forum Java Theory & Questions
    Replies: 3
    Last Post: April 28th, 2011, 07:39 AM