Link to home
Start Free TrialLog in
Avatar of LearningJava
LearningJava

asked on

Variable array size

Hi:

I need to match the array size with a variable size input file.How would I accomplish this task?

import java.util.Comparator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import java.util.Arrays;

/**
@author LearningJava
A telephone lookup program.
@version 1.0
*/
public class Telephone
{  public static void main(String[] args)
   {  ConsoleReader console = new ConsoleReader(System.in);
      System.out.print ("Enter the file name where the address book"
        + " is stored: ");
      String fileName = console.readLine();
      if (fileName == null)
      System.exit(0);
             
      PhoneBook people [] = new PhoneBook[ARRAY_SIZE];
               
      try
      {  FileReader fr = new FileReader(fileName);
         BufferedReader in  = new BufferedReader(fr);
         boolean more = true;
         int count = 0;
         while (more && count < people.length)
         {  
            String k = in.readLine();
            String v = null;
            if (k != null) v = in.readLine();
            if (v != null)
            {  
               people[count] = new PhoneBook(k, v);
               count++;
            }
            else more = false;
         }
         
         in.close();
      }
      catch (IOException exception)// Is this complete?
      {  
         System.out.println(exception);
         System.exit(1);
      }
                 
      System.out.println("Search choice: 1)name, 2)number");
      String choice = console.readLine ();
     
      if (choice.equals("1"))
      {        
         System.out.println ("Name:");
         String name = console.readLine ();
         Comparator fullName = new FullNameComp();
     
         Arrays.sort(people, fullName);
         Keyword kw = new Keyword(name);
         Comparator nameLookup = new NameLookup();  
         int foundIndex = Arrays.binarySearch(people, kw, nameLookup);

         if (foundIndex >= 0)
         {
            System.out.println(people[foundIndex]);
         }
         else
         {
            System.out.println("Name:  " + kw + "' not found in the phonebook");
         }
           
       }
     
       if (choice.equals("2"))
       {
          System.out.println ("Number:");
          String phoneNumber = console.readLine ();
          Comparator numSort = new NumberSort();
          Arrays.sort(people, numSort);
       
          Keyword kw2 = new Keyword(phoneNumber);
          Comparator numLookup = new ReverseLookup();
          int foundIndex2 = Arrays.binarySearch(people, kw2, numLookup);
       
          if (foundIndex2 >= 0)
          {
             System.out.println(people[foundIndex2]);
          }
          else
          {
             System.out.println("Number:  " + kw2 + " not found in the"
               + "phonebook");
          }
           
      }          
          System.exit(0);

   }  
   private static final int  ARRAY_SIZE = 8;
     
}  


/**
Describes a Telephone book.
@author LearningJava
@version 1.0
*/

class PhoneBook
{

   /**
   Constructor for a phonebook.
   @param name     A person's full name.
   @param number   The phone number.
   */

   public PhoneBook(String name, String number)
   {
      fullName = name;
      phoneNum = number;

   }

   /**
   Method(accessor) to get full name.
   @return fullName  The full name.
   */
   public String getName()
   {
      return fullName;
   }

   /**
   Method(accessor)to get the telephone number.
   @return phoneNum  The telephone number.
   */
   public String getNumber()
   {
      return phoneNum;
   }

   /**
   Method(mutator) to alter the fullName.
   @param fullName  A person's full name.
   */
   public void setFullName(String fullName)
   {
      this.fullName = fullName;
   }

   /**
   Method(mutator)to alter the phone number.
   @param phoneNumber   The phone number.
   */
   public void setPhoneNumber(String phoneNumber)
   {
      this.phoneNum = phoneNum;
   }


   /**
   Method to return a string.
   @return The phonebook as a string.
   */

   public String toString()
   {
      return fullName + " " + phoneNum;
   }

   private String fullName;
   private String phoneNum;

}


/**
Describes a Keyword.
@author LearningJava
@version 1.0
*/
class Keyword
{

   /**
   Constructor for a Keyword.
   @param key The keyword.
   */
   public Keyword(String key)
   {

      this.key = key;

   }

   /**
   Method to get keyword.
   @return key  The keyword.
   */
   public String getKey()
   {
      return key;
   }

   /**
   Method to return a string.
   @return The key as a string.
   */

    public String toString()
    {
       return key;
    }
 
    private String key;

}


/**
A class that implemements the Comparator interface for sorting
PhoneBook objects.
@author LearningJava
@version 1.0
*/
class FullNameComp implements Comparator
{

   /**
   A method that compares arguments(compareTo method of the String class)
   for natural order(ascending)based on full name.

   @param obj1 The first object.
   @param obj2  The second object.
   @return     A negative integer, zero, or a positive integer as this
               object is less than, equal to, or greater than the
               specified object.
   */
   public int compare(Object obj1, Object obj2)
   {  
     
      PhoneBook people1 = (PhoneBook) obj1;
      PhoneBook people2 = (PhoneBook) obj2;
      return people1.getName().compareTo(people2.getName());
   }

}


/**
A class that implemements the Comparator interface for sorting objects.
@author LearningJava
@version 1.0
*/
class NameLookup implements Comparator
{
   /**
   A method that compares arguments for natural order.
   @param obj1 The first object.
   @param obj2  The second object.
   @return     A negative integer, zero, or a positive integer as this
               object is less than, equal to, or greater than the
               specified object.
   */
   public int compare(Object obj1, Object obj2)
   {        
     
      PhoneBook phonebook = (PhoneBook) obj1;
      Keyword keyword = (Keyword) obj2;
      return (phonebook.getName()).compareTo(keyword.getKey());
   
   }

}


/**
A class that implemements the Comparator interface for sorting objects.
@author LearningJava
@version 1.0
*/
class NumberSort implements Comparator
{
   /**
   A method that compares arguments for natural order based on phone
   number.
   @param obj1 The first object.
   @param obj2  The second object.
   @return     A negative integer, zero, or a positive integer as this
               object is less than, equal to, or greater than the
               specified object.
   */
   public int compare(Object obj1, Object obj2)
   {  
             
      PhoneBook people1 = (PhoneBook) obj1;
      PhoneBook people2 = (PhoneBook) obj2;
      return people1.getNumber().compareTo(people2.getNumber());
   }

}


/**
A class that implemements the Comparator interface for sorting objects.
@author LearningJava
@version 1.0
*/
class ReverseLookup implements Comparator
{
   /**
   A method that compares arguments for natural order.
   @param obj1 The first object.
   @param obj2  The second object.
   @return     A negative integer, zero, or a positive integer as this
               object is less than, equal to, or greater than the
               specified object.
   */
   public int compare(Object obj1, Object obj2)
   {
               
       PhoneBook phonebook = (PhoneBook) obj1;
       Keyword keyword = (Keyword) obj2;
       return (phonebook.getNumber()).compareTo(keyword.getKey());
   
   }

}





Avatar of girionis
girionis
Flag of Greece image

 Do you mean you need to create an array with equal size sa a file? If yes then get the file length in bytes and create the array out of it:

  byte [] legthOfFile = new byte[file.length]

  where "file" is the instance of yor file object.
Avatar of LearningJava
LearningJava

ASKER

No, I mean I need an array which will equal a variable number of objects that contain a name and phone number?
 Do you know in advance how many objects that contain name and phone number you will have? If you do you just do:

  Object [] myArray = new Object[<number of objects that contain name and phone number>];

 
No, the user would not know this information in advance.
Don't bother...

Just use java.util.ArrayList whilst you read them in,
Then, you can do:

PhoneBook[] people = (PhoneBook[])arrayList.toArray() ;              

Easy peasy :-)
I tried using a vector but I get the following error:

Telephone.java:64: Incompatible type for method. Can't convert java.util.Vector to java.lang.Object[].

         Arrays.sort(people, fullName);

                     ^

Telephone.java:67: Incompatible type for method. Can't convert java.util.Vector to java.lang.Object[].

         int foundIndex = Arrays.binarySearch(people, kw, nameLookup);

                                              ^

Telephone.java:71: [] can only be applied to arrays. It can't be applied to java.util.Vector.

            System.out.println(people[foundIndex]);

                                     ^

Telephone.java:85: Incompatible type for method. Can't convert java.util.Vector to java.lang.Object[].

          Arrays.sort(people, numSort);

                      ^

Telephone.java:89: Incompatible type for method. Can't convert java.util.Vector to java.lang.Object[].

          int foundIndex2 = Arrays.binarySearch(people, kw2, numLookup);

                                                ^

Telephone.java:93: [] can only be applied to arrays. It can't be applied to java.util.Vector.

             System.out.println(people[foundIndex2]);

                                      ^

6 errors



-----------------------------------------------------------------------------
Double click on the line with file name
and error number to locate the error.





      Vector people = new Vector();      
      //PhoneBook people [] = new PhoneBook[ARRAY_SIZE];
               
      try
      {  FileReader fr = new FileReader(fileName);
         BufferedReader in  = new BufferedReader(fr);
         boolean more = true;
         int count = 0;
         while (more)
         {  
            String k = in.readLine();
            String v = null;
            if (k != null) v = in.readLine();
            if (v != null)
            {  
               people.add(new PhoneBook(k, v));          
               count++;
            }
            else more = false;
         }
         
         in.close();

 Then you can't do it with arrays since you cannot change their size dynamically. Use other containers to do it, Vector, List ,Collection, Arrays.
 You can't use a Vector where an Object array is expected. Look at TimYates' suggestion.
Hi Tim:
       Is that the only change required in my program
 

"Just use java.util.ArrayList whilst you read them in,
Then, you can do:

PhoneBook[] people = (PhoneBook[])arrayList.toArray() ;"              



Think so...
ASKER CERTIFIED SOLUTION
Avatar of TimYates
TimYates
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
When I make the code change I get the following error:

Telephone.java:27: Can't make static reference to method java.lang.Object toArray()[] in class java.util.ArrayList.

        PhoneBook[] people = (PhoneBook[])ArrayList.toArray();        



 YOu need to create an instance of the ArrayList.
 You will also need to add every single PhoneBook object into the ArrayList instance by using its add(Object) method before you can turn it into an array.
 ... like suggested above :-)
I changed code but I am still getting error messages:

Telephone.java:27: Undefined variable or class name: arrayList

        PhoneBook[] people = (PhoneBook[])arrayList.toArray();                            ^
Telephone.java:41: Undefined variable or class name: arrayList
 arrayList.add( new PhoneBook( k, v ) ) ;          
2 errors



-----------------------------------------------------------------------------
Double click on the line with file name
and error number to locate the error.



  PhoneBook[] people = (PhoneBook[])arrayList.toArray();        
      try
      {  FileReader fr = new FileReader(fileName);
         BufferedReader in  = new BufferedReader(fr);
         boolean more = true;
         int count = 0;
         while (more && count < people.length)
         {  
            String k = in.readLine();
            String v = null;
            if (k != null) v = in.readLine();
            if (v != null)
            {  
             
               arrayList.add( new PhoneBook( k, v ) ) ;          
               count++;
            }
            else more = false;

Where did yo create an instance of arrayList. I thing you are not doing it any where and not defining the variable arrayList
"Where did yo create an instance of arrayList. I thing you are not doing it any where and not defining the variable arrayList"

Please demonstrate with code.

java.util.ArrayList arrayList = new java.util.ArrayList();

?
I followed the advice given. The code compiled without error but I got the following error when reading a file:

Enter the file name where the address book is stored: c:\numbers.txt
java.lang.ClassCastException
at Telephone.main(Telephone.java, Compiled Code)
Exception in thread "main" Process Exit...


 ArrayList  arrayList   =  new  ArrayList();              
       PhoneBook[] people = (PhoneBook[])arrayList.toArray();        
      try
      {  FileReader fr = new FileReader(fileName);
         BufferedReader in  = new BufferedReader(fr);
         boolean more = true;
         int count = 0;
         while (more && count < people.length)
         {  
            String k = in.readLine();
            String v = null;
            if (k != null) v = in.readLine();
            if (v != null)
            {  
             
               arrayList.add( new PhoneBook( k, v ) ) ;          
               count++;
            }
            else more = false;
         }
         
         in.close();

PhoneBook[] people = (PhoneBook[])arrayList.toArray();    
This should be at the end i thing
....
         arrayList.add( new PhoneBook( k, v ) ) ;          
              count++;
           }
           else more = false;
        }
PhoneBook[] people = (PhoneBook[])arrayList.toArray();    
in.close();

and in the while loop

i did not understand
while (more && count < people.length)
       
why you need count < people.length

maybe just use
while(more)
yes, or preferably just after in.close();
(i like to open and close files as quickly as possible)
I have made the change but I still get the following error message at runtime:

Enter the file name where the address book is stored: c:\numbers.txt
java.lang.ClassCastException

     at Telephone.main(Telephone.java, Compiled Code)

Exception in thread "main" Process Exit...

try to debug and see where the error is or put some print statements before the loop inside the loop and outside.

The loop seems to be ok and there might be error somewhere else
I got it to work. The code is as follows:ArrayList  arrayList   =  new  ArrayList();              
               
      try
      {  FileReader fr = new FileReader(fileName);
         BufferedReader in  = new BufferedReader(fr);
         boolean more = true;
         int count = 0;
         while (more)
         {  
            String k = in.readLine();
            String v = null;
            if (k != null) v = in.readLine();
            if (v != null)
            {  
             
               arrayList.add( new PhoneBook( k, v ) ) ;          
               count++;
            }
            else more = false;
         }
             

         in.close();
         
      }
      catch (IOException exception)// Is this complete?
      {  
         System.out.println(exception);
         System.exit(1);
      }
     
     
      int arrayListSize = arrayList.size();
           
      PhoneBook[] people = new PhoneBook[arrayListSize];
      people = (PhoneBook[]) arrayList.toArray(people);
               
      System.out.println("Search choice: 1)name, 2)number");
      String choice = console.readLine ();

That's the fella :-)
Why have the irritating 'schizoid' problem of having PhoneBook[] *and* a Collection. Why not just use the Collection (ArrayList) alone?
Because I learning java and I don't know any better.