6 Replies - 619 Views - Last Post: 17 June 2012 - 02:34 PM Rate Topic: -----

#1 AllHighway  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 54
  • Joined: 08-February 12

Help with using arrays to creat objects from a text file

Posted 08 June 2012 - 04:48 PM

I am trying to create several arrays from a text file to sort. I am not exactly sure how to split the information up into categories. The text file I am pulling the information from is separated in five categories. This is an example.
Norway Oslo Northern_Europe 1 480000
Italy Rome Western_Europe 2 2700000
Austria Vienna Central_Europe 4 1600000
Poland Warsaw Central_Europe 4 1660000
Sweden Stockholm Northern_Europe 1 720000

This is what is being asked from my professor:
"1. Build Array of Country Objects. Using input file, you are to build an array of objects. You are to design and develop a class named Country (in addition to your class named Main) and create the number of objects of type (class) Country - one object for each record (line) from the input file. You need to use Buffered Reader, etc. as found (examples on Brief Introduction to Input/Output slide 7)) on my web page. Do not use Scanner.

Each Country object will have five properties defined individually as integers or Strings as appropriate for each Country object attribute. You should download this file and use this as input to your program to create the array of Country objects."



This is my code I have written already to pull the information as a whole from the text file.
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package project1barry;
import  java.io.*;


/**
 *
 * @author Jason
 */
public class Country {

    private String path;
    
    public Country (String file_path) {
        path=file_path;
        
    }

    public String [] OpenFile () throws IOException {
           
        FileReader fr = new FileReader (path);
        
        BufferedReader textReader = new BufferedReader (fr);
        
        int numberOfLines = readLines ();
        String[ ] textData = new String[numberOfLines];
        
        int i;
        
        for (i=0; i < numberOfLines; i++) {
            textData[i] =textReader.readLine();
            
        }
        textReader.close();
        return textData;
        }

        int readLines() throws IOException {

            FileReader file_to_read = new FileReader (path);
            BufferedReader bf = new BufferedReader (file_to_read);

            String aLine;
            int numberOfLines = 0; 
            
            while ((aLine= bf.readLine()) != null) {
            numberOfLines++;
            }
            
            bf.close();
        
            return numberOfLines;
        }
        
}


Any direction will be appreciated. Thank you in advanced.

This post has been edited by AllHighway: 08 June 2012 - 04:49 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Help with using arrays to creat objects from a text file

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10364
  • View blog
  • Posts: 38,375
  • Joined: 27-December 08

Re: Help with using arrays to creat objects from a text file

Posted 08 June 2012 - 05:49 PM

It looks like your Country objects should have five attributes: name, capital, region, id, and population. Take a look at my tutorial Moving Away From Parallel Arrays for how to design the class. I would also suggest moving the File I/O portion out of the Country class, and using another class to create your Country objects. It's cleaner and more organized this way. You don't want to over-complicate the Country class with more responsibilities than simply modeling a Country.
Was This Post Helpful? 0
  • +
  • -

#3 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1148
  • View blog
  • Posts: 2,522
  • Joined: 05-May 05

Re: Help with using arrays to creat objects from a text file

Posted 08 June 2012 - 08:15 PM

Your supposed to parse a line from the file, split it into 5 strings (1 per category) and use those strings to initialize a new Country object, which will be added to the array.
Was This Post Helpful? 0
  • +
  • -

#4 AllHighway  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 54
  • Joined: 08-February 12

Re: Help with using arrays to creat objects from a text file

Posted 09 June 2012 - 03:21 AM

Thanks guys. I just got off work and I am ready for bed. I will work on this when I wake up.
Was This Post Helpful? 0
  • +
  • -

#5 AllHighway  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 54
  • Joined: 08-February 12

Re: Help with using arrays to creat objects from a text file

Posted 12 June 2012 - 12:24 AM

Ok I got the attributes parsed and I need to create an array for each attribute. Mac, I appreciate the tutorial, but I am having trouble understanding it. Do I need to create a country class and define my attributes in that class and then create another class to implement the array? I know I need to make the arrays of the country's attributes but I am having some trouble wrapping my brain around it. Thanks and I will study your tutorial further.
Was This Post Helpful? 0
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Help with using arrays to creat objects from a text file

Posted 12 June 2012 - 08:01 AM

View PostAllHighway, on 12 June 2012 - 03:24 AM, said:

Do I need to create a country class and define my attributes in that class and then create another class to implement the array?

That will be the best approach. Later on, if you read your data from a database, you can just write a new class DBReader that will be able to use the already existing Country class
Was This Post Helpful? 0
  • +
  • -

#7 AllHighway  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 54
  • Joined: 08-February 12

Re: Help with using arrays to creat objects from a text file

Posted 17 June 2012 - 02:34 PM

OK i worked through it. Now I need to do binary search. This is what I have for my CollectionClass. I am getting errors in the binaySearch method. It says I have to initialize the int i and int j. I have been looking at this for awhile and cant figure it out. Any ideas/suggestions on this or is there a simpler way to do this binary search? Thanks in advanced.
package project1barry;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;




/**
 *
 * @author Jason
 */




public class CountryCollection 
{
        private CountryData[] country;
        private String [] searchTerms;
        private String inputString;//Reads the text file as strings.
        private String CountryName;
        private String CountryCapital;
        private String CountryRegion;//String variables.
        private int    CountryPopulation;
        private int    CountryRegionNbr;//Integer variables.
        private int    nElem;
        private int    nSearchTerms;
        
    public CountryCollection(int Max) 
    {
     nElem = Max;
     country= new CountryData [Max];
  //-----------------------------------------------------------------------           
          
    }
    public void LoadData(int nElem, String line)
    {
            inputString=line;
            CountryName=inputString.substring(0, 23).trim();//Reads country name.
            CountryCapital=inputString.substring(24, 39);//Reads county capital.     
            CountryRegion=inputString.substring(40, 63);//Reads country region.
            CountryRegionNbr= Integer.parseInt(inputString.substring(64, 71).trim());//Reads country population.
            CountryPopulation= Integer.parseInt (inputString.substring(72).trim());//Reads country region number.
            country [nElem]= new CountryData (CountryName, CountryCapital, CountryRegion, CountryRegionNbr, CountryPopulation);

            
   //-----------------------------------------------------------------------          
     }
     public CountryData getCountryObject (int nElem)
     {
         CountryData carray = country[nElem];
         return carray;
     }
  //-----------------------------------------------------------------------    
     public void sort()
     {
         int in;
         int out;
         for(out=nElem-1; out>1; out--) 
             for(in=0; in<out; in++)
            if( country[in].getCountryName().compareTo(country[in+1].getCountryName())>0 )
                swap(in, in+1);
     }
    
   //-----------------------------------------------------------------------         
      public void swap(int one, int two)
      {    
      CountryData temp = country[one];
      country[one] = country[two];
      country[two]=temp;
      }
  //-----------------------------------------------------------------------     
      public void OpenFile () throws IOException
      {
        String strLine;
        nSearchTerms = 0;
        FileReader in = new FileReader("Search.Trans.Summer2012.txt");
        BufferedReader br = new BufferedReader(in);
 
        
        searchTerms = new String[20];
        strLine = br.readLine();
        
        while (strLine != null) 
        {    
            searchTerms[nSearchTerms] = strLine.trim();
            nSearchTerms++;
            strLine = br.readLine();
        }
        
        //System.out.println("count: "+nSearchTerms);
        in.close();
        
        //for (int i = 0; i < nSearchTerms; i++)
        //System.out.println(searchTerms[i]);
      } 
//-----------------------------------------------------------------------          
      public void display()
      {
          System.out.println ("Country\t\t"+"Capital\t\t"+"Region\t\t"+"Region Number\t\t"+"Capital Population\t\t\n\n");
          for (int i=0; i < 43; i++)
              System.out.println (country[i]);
              System.out.println("");
      }
 //-----------------------------------------------------------------------     
 
      public void sequentialSearch()
      {
          String find;
          int j;
          int i;
          int probes;
          int finalProbe;
         
                                    
      System.out.println("Search Key\t\t"+"Probes\t\t"+"Found or Not Found\t\t\n\n");
      for(j=0; j<nSearchTerms; j++)// for each element
      {
         find=null;
         probes=0;
         for(i=0;i<nElem;i++)
         {
             probes++;
             
             if (country[i].getCountryName().compareTo(searchTerms[j])==0) 
             {
                 find = "Found";
                 break;
             }
             else 
                 find = "Not found";
         }// end inner for loop
         
         System.out.println(searchTerms[j] + "\t" + probes + "\t"+ find);
         
       }// end outer for loop
       
      }// end search method
//------------------------------------------------------------------------------
         
      public void binarySearch()
      {
          String find;
          int lowerBound = 0;
          int upperBound = nElem-1; 
          int i;
          int j;
          int probes=1;
          System.out.println("Search Key\t\t"+"Probes\t\t"+"Found or Not Found\t\t\n\n");

          while (country[i].getCountryName().compareTo(searchTerms[j])!=0)
              
          {
             
              probes++;
                if(country[i].getCountryName().compareTo(searchTerms[j])>0)
                {
               upperBound = i - 1;
                }
               else 
                {
                    lowerBound = i + 1;
                }
                    
              i = (lowerBound + upperBound)/2;
          }
          if
             (lowerBound <= upperBound)
          {
            
              
              
              //(country[i].getCountryName().compareTo(searchTerms[j])<0) 
               // probes++;
              //else  
              //{
                  
                      
                  //else
                      
                 
          }  //}
              find=null;
              find = "Not Found";
              System.out.println(searchTerms[j] + "\t" + probes + "\t"+ find);
           //end while loop
          
       }//end binary search method
      
}//end class
       
          
          
          
          
 
  
    

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1