1 2 3 Previous Next 44 Replies Latest reply: Jul 29, 2007 11:36 PM by 3004 RSS

    Need to locate a record in an array and return a value, then loop

    807600
      as part of an assignment (so I'm posting generic code here) I need to perform the following task:

      lookup a String from and array and return a double from the same array before repeating the whole procedure until the user inputs an empty String

      Here is what I have:
      // create the array
      BaseClass[] myArray = new BaseClass[6];
      // populate the array
      /*  the constructors for the array
      myArray[i] = new DeriviativeClass(String a,String b,int p,String c)
      myArray[i] = new BaseClass(String a,String b,int p)
      */
      myArray[0]=new DeriviativeClass("C001","stringB1",1,"stringC1");
      myArray[1]=new BaseClass("B001","stringB2",1);
      myArray[2]=new DeriviativeClass("C002","stringB3",4,"stringC2");
      myArray[3]=new DeriviativeClass("C003","stringB4",4,"stringC3");
      myArray[4]=new BaseClass("B002","stringB5",2);
      myArray[5]=new BaseClass("B003","stringB6",4);
      /* myMethod() is a method from BaseClass */
      double result = myArray.myMethod();
      String myMessage = "Error message";
      // begin loop
      // get the string to search for
      Scanner sc = new Scanner(System.in);
      System.out.print("Enter a String: ");
      String searchString = sc.nextLine();
      searchString = searchString.toUpperCase();     
      /* this is the area where I need help */
      // end loop     
      I need to search 'String a' for the value of 'searchString' then print the value of 'result', if 'searchString' isn't found, I need to print 'myMessage'. The loop has to repeat until
      (searchString.length()=0)
        • 1. Re: Need to locate a record in an array and return a value, then loop
          3004
          Neither your requirements nor the problem you're having are clear.
          • 2. Re: Need to locate a record in an array and return a value, then loop
            807600
            my apologies

            The task :
            Implement another code segment (feature) which uses a loop to repeatedly
                 * prompt the user for a booking ID, after which it searches for an object in
                 * the array with the id specified and displays the total cost of the booking
                 * (if it is found).

            I can't get the search and display part to work correctly:
            import java.io.*;
            import java.util.*;
            public class HelpPlease 
            {
                 public static void main(String[] args)  throws IOException
                 {
                      Booking[] myArray = new Booking[6];
                      /* populate the Array we are going to search  */
                      myArray[0]=new CabinBooking("C001","stringB1",1,"stringC1");
                      myArray[1]=new Booking("B001","stringB2",1);
                      myArray[2]=new CabinBooking("C002","stringB3",4,"stringC2");
                      myArray[3]=new CabinBooking("C003","stringB4",4,"stringC3");
                      myArray[4]=new Booking("B002","stringB5",2);
                      myArray[5]=new Booking("B003","stringB6",4);
            
            
                      /* define the variables we will be using */
                      int i=0;
                      double[] price = new double[6]; 
                      for (i=0;i<6;i++)
                           price[i] = myArray.calculateBookingPrice();
                      String searchString=null;
                      Scanner sc = new Scanner(System.in);
                      // the message to display if an incorrect Booking ID is entered
                      String notFound = ("Error: Booking ID "+searchString+" not found!");
                      
                      /* Begin the search Loop
                      *
                      * request the search String (done)
                      * assign the searchString (done)
                      * search the array
                      *           if found; print ("$"+price)
                      *           if not found; print (notFound)
                      * repeat the loop until the user enters a null string
                      */
                      System.out.print("Enter a Booking ID: ");
                      searchString = sc.nextLine();
                      searchString = searchString.toUpperCase();     
                      /* I don't understand how to search the array:
                      * the notFound message should only print once
                      * for each searchString
                      */
                 }
            }does that help clarify things?
            • 3. Re: Need to locate a record in an array and return a value, then loop
              807600
              Hi,

              I'm very sure what you want, does you mean like tiz
                        boolean found = false;
                        System.out.print("Enter a Booking ID: ");
                        searchString = sc.nextLine();
                        if(searchString!=("")) {
                             for(int j=0; j<6; j++) {
                                  if(searchString.equals(myArray[j])) {
                                       found = true;
                                  }
                             }               
                             if(found == false) {
                                  System.out.println(notFound);
                             } else if(found == true){
                                  System.out.println("Record found");     //("$"+price)
                             }
                        } else {
                             return;
                        }
              • 4. Re: Need to locate a record in an array and return a value, then loop
                807600
                String notFound = ("Error: Booking ID "+searchString+" not found!");
                You might want to move this line after you have read in the searchString.

                Everything doesn't have to be in the main method. Try breaking your program into smaller chunks and place these chunks into separate methods.
                • 5. Re: Need to locate a record in an array and return a value, then loop
                  3004
                  I can't get the search and display part to work
                  correctly:
                  Exactly what is going wrong?
                  • 6. Re: Need to locate a record in an array and return a value, then loop
                    3004
                    Everything doesn't have to be in the main method. Try
                    breaking your program into smaller chunks and place
                    these chunks into separate methods.
                    Seconded!
                    • 7. Re: Need to locate a record in an array and return a value, then loop
                      807600
                      How do I break my main() method into smaller chunks?
                      I tried but my IDE (Eclipse) just shows me squiggly lines and warnings and I don't know how to rectify them ...
                      I can find their location, but I don't know what to do to fix them
                      Example:
                      public static double getPrice()
                      {
                         int i=0;
                         double[] price = new double[6];
                         // fill the priceArray          
                         for (i=0;i<6;i++)
                         {
                            if (ticket[i] instanceof CabinBooking)
                            {
                               price[i] = ((CabinBooking)ticket).calculateBookingPrice();
                      }
                      else if (ticket[i] instanceof Booking)
                      {
                      price[i] = ((Booking)ticket[i]).calculateBookingPrice();
                      }
                      }

                      }
                      results in squiggles under ' double getPrice() '

                      Message was edited by:
                      kcstingel
                      • 8. Re: Need to locate a record in an array and return a value, then loop
                        807600
                        as much as i understood in your code booking is a parent class for cabinbooking and things like this. here the code becomes polymorphic and you shouldn't need to chechk its instance, you can call calculatebooking methods without if and else if :
                           for (i=0;i<6;i++)
                           {
                               price[i] =ticket.calculateBookingPrice(); 
                        }

                        and for searching you can crate a new object with your string and you can make a for loop in which you can try newobject.equals(array[i]);
                        if you are having problem with the equals method you can override it
                        • 9. Re: Need to locate a record in an array and return a value, then loop
                          807600
                          I almost have it <smiles>
                          here is the code I plan to submit (when fixed) ... the error I'm getting is explained underneath.
                          public class TicketApp
                          {
                             
                             /**
                              * @param args
                              */
                             public static void main(String[] args)  throws IOException
                             {
                                /**
                                 * (i) Define an array of Booking references that can store up to six
                                 * objects (elements).
                                 */
                                Booking[]ticket = new Booking[6];
                                /**
                                 * (ii) Create the Booking and CabinBooking objects specified below and
                                 * store them in the array of Booking references mentioned above ? you
                                 * should pass the values shown below as arguments to the constructor when
                                 * creating each of the objects.
                                 */
                                ticket[0] = new CabinBooking("C001","Dorothy the Dinosaur",1,"C23");
                                ticket[1] = new Booking("B001","Bob the Builder",1);
                                ticket[2] = new CabinBooking("C002","Donald Duck",4,"B10");
                                ticket[3] = new CabinBooking("C003","The Wiggles",4,"D14");
                                ticket[4] = new Booking("B002","Mickey Mouse",2);
                                ticket[5] = new Booking("B003","Hi Five (Minus One)",4);
                                /**
                                 * (iii) Implement a code segment (feature) which displays the booking ID
                                 * and name for all Booking and CabinBooking objects by using a loop to
                                 * step through each of the objects in the array and calling the summary()
                                 * method for each object in an appropriate fashion.
                                 */ 
                                System.out.println("List of Booking Id's and Names:");
                                System.out.println(); 
                                for (int i=0;i<6; i++) 
                                {
                                   System.out.printf("%-16s%-6s", "Booking Number: ",ticket.getBookingID());
                          System.out.printf("%-18s%s\n", "Name on Booking: ",ticket[i].getBookingName());
                          }
                          System.out.println();

                          /**
                          * (iv) Implement another code segment (feature) which uses a loop to
                          * repeatedly prompt the user for a booking ID, after which it searches
                          * for an object in the array with the id specified and displays the total
                          * cost of the booking (if it is found).
                          */
                          System.out.println("Booking Price Retrieval: ");
                          System.out.println();
                          Scanner sc = new Scanner(System.in);
                          System.out.print("Enter a Booking ID: ");
                          String searchString = sc.nextLine();
                          searchString = searchString.toUpperCase();
                          do
                          {
                          double[] price = new double[6];
                          for (int i=0;i<6;i++)
                          {
                          if(searchString.equals(ticket[i].getBookingID()))
                          {
                          if (ticket[i] instanceof CabinBooking)
                          {
                          price[i] = ((CabinBooking)ticket[i]).calculateBookingPrice();
                          }
                          else if (ticket[i] instanceof Booking)
                          {
                          price[i] = ((Booking)ticket[i]).calculateBookingPrice();
                          }
                          System.out.printf("%-23s%s%.2f\n", "Price of Ticket: ","$",price[i]);
                          }
                          else
                          {
                          System.out.println("Error: Booking ID "+searchString+" not found!");      
                          }
                          System.out.print("Enter a Booking ID: ");
                          searchString = sc.nextLine();
                          searchString = searchString.toUpperCase();
                          }
                          }
                          while (searchString.length()!=0);     
                          // design time notification of loop closure
                          System.out.println("Loop complete!");
                          /**
                          * (v) Implement another code segment (feature) which upgrades the
                          * CabinBooking objects stored in the array so that dinner is included by
                          * invoking the upgradeBooking() method for each object in an appropriate
                          * fashion.
                          */ /*
                          for (int i=0;i<6; i++)
                          {
                          if (ticket[i] instanceof CabinBooking)
                          ((CabinBooking)ticket[i]).upgradeBooking();
                          */     
                          /**
                          * (vi) Implement a final code segment which uses a loop to step through
                          * the array of objects and displays the details for each object by
                          * invoking the summary() method defined in the data classes in an
                          * appropriate fashion.
                          */
                          System.out.println("Full Booking Details:");
                          for (int i=0;i<6;i++)
                          {
                          ticket[i].summary();
                          }
                          }
                          }as we are supposed to re-use code where possible, I would like to be able to reference the lookup to
                          ticket.getBookingID()) further down in my search section; but everytime I try to build an accessor to it, the little squiggles come back.

                          The search section is iterating through 6 times regardless of a null string for user input ... and gives the error message unless the correct corresponding data for that position in the array is given
                          • 10. Re: Need to locate a record in an array and return a value, then loop
                            800282
                            Not related to the problem you're having at the moment but looking at this code:
                                           if (ticket[i] instanceof CabinBooking)
                                           {
                                              price[i] = ((CabinBooking)ticket).calculateBookingPrice();
                            }
                            else if (ticket[i] instanceof Booking)
                            {
                            price[i] = ((Booking)ticket[i]).calculateBookingPrice();
                            }makes me wonder: doesn't CabinBooking extend Booking? If so, why are you using the instanceof operator here? You could just do:
                            price[i] = ticket.calculateBookingPrice();, right?

                            Edit: Oh, wait, they probably both extend/implement BaseClass. In that case the calculateBookingPrice() method should be defines/implemented in that BaseClass.
                            • 11. Re: Need to locate a record in an array and return a value, then loop
                              807600
                              calculateBookingPrice() was overridden in CabinBooking (to reflect the price of the cabin) so each Booking type has it's own calculation method
                              • 12. Re: Need to locate a record in an array and return a value, then loop
                                800282
                                calculateBookingPrice() was overridden in
                                CabinBooking (to reflect the price of the cabin) so
                                each Booking type has it's own calculation method
                                My point still stands: there is no need for the instanceof operator and those castings.
                                • 13. Re: Need to locate a record in an array and return a value, then loop
                                  800308
                                         * step through each of the objects in the array and calling the summary()
                                         * method for each object in an appropriate fashion.
                                         */ 
                                        System.out.println("List of Booking Id's and Names:");
                                        System.out.println(); 
                                        for (int i=0;i<6; i++) 
                                        {
                                           System.out.printf("%-16s%-6s", "Booking Number: ",ticket.getBookingID());
                                  System.out.printf("%-18s%s\n", "Name on Booking: ",ticket[i].getBookingName());
                                  }
                                  System.out.println();


                                  I don't see a call to the summary() method. 5 marks off.

                                  Message was edited by: corlettk

                                  BTW... typically a toString() method is provided which formats this object into a "display" string.
                                  • 14. Re: Need to locate a record in an array and return a value, then loop
                                    800308
                                    kc,

                                    Do you understand prometheuzz's point... it's a rather importance one in OO land.
                                    1 2 3 Previous Next