?
Solved

Variable array size

Posted on 2003-03-09
29
Medium Priority
?
210 Views
Last Modified: 2010-03-31
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());
   
   }

}





0
Comment
Question by:LearningJava
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 11
  • 7
  • 4
  • +3
29 Comments
 
LVL 35

Expert Comment

by:girionis
ID: 8098896
 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.
0
 

Author Comment

by:LearningJava
ID: 8098926
No, I mean I need an array which will equal a variable number of objects that contain a name and phone number?
0
 
LVL 35

Expert Comment

by:girionis
ID: 8098955
 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>];

 
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:LearningJava
ID: 8098994
No, the user would not know this information in advance.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 8099005
Don't bother...

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

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

Easy peasy :-)
0
 

Author Comment

by:LearningJava
ID: 8099007
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();

0
 
LVL 35

Expert Comment

by:girionis
ID: 8099012
 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.
0
 
LVL 35

Expert Comment

by:girionis
ID: 8099018
 You can't use a Vector where an Object array is expected. Look at TimYates' suggestion.
0
 

Author Comment

by:LearningJava
ID: 8099036
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() ;"              



0
 
LVL 35

Expert Comment

by:TimYates
ID: 8099051
Think so...
0
 
LVL 35

Accepted Solution

by:
TimYates earned 900 total points
ID: 8099059
Oh, and:

              people[count] = new PhoneBook(k, v);

to

  arrayList.add( new PhoneBoox( k, v ) ) ;
0
 

Author Comment

by:LearningJava
ID: 8099061
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();        



0
 
LVL 35

Expert Comment

by:girionis
ID: 8099070
 YOu need to create an instance of the ArrayList.
0
 
LVL 35

Expert Comment

by:girionis
ID: 8099081
 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.
0
 
LVL 35

Expert Comment

by:girionis
ID: 8099088
 ... like suggested above :-)
0
 

Author Comment

by:LearningJava
ID: 8099492
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;

0
 
LVL 2

Expert Comment

by:navneet77
ID: 8099585
Where did yo create an instance of arrayList. I thing you are not doing it any where and not defining the variable arrayList
0
 

Author Comment

by:LearningJava
ID: 8099638
"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.

0
 
LVL 1

Expert Comment

by:hj2k3
ID: 8099777
java.util.ArrayList arrayList = new java.util.ArrayList();

?
0
 

Author Comment

by:LearningJava
ID: 8099802
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();

0
 
LVL 2

Expert Comment

by:navneet77
ID: 8099815
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();

0
 
LVL 2

Expert Comment

by:navneet77
ID: 8099825
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)
0
 
LVL 1

Expert Comment

by:hj2k3
ID: 8099826
yes, or preferably just after in.close();
(i like to open and close files as quickly as possible)
0
 

Author Comment

by:LearningJava
ID: 8099916
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...

0
 
LVL 2

Expert Comment

by:navneet77
ID: 8099958
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
0
 

Author Comment

by:LearningJava
ID: 8100135
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 ();

0
 
LVL 35

Expert Comment

by:TimYates
ID: 8101710
That's the fella :-)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8101959
Why have the irritating 'schizoid' problem of having PhoneBook[] *and* a Collection. Why not just use the Collection (ArrayList) alone?
0
 

Author Comment

by:LearningJava
ID: 8102671
Because I learning java and I don't know any better.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses
Course of the Month10 days, 10 hours left to enroll

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question