Reading from File and Storing in Array [HELP]
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6

Thread: Reading from File and Storing in Array [HELP]

  1. #1
    Join Date
    Jan 2010
    Posts
    3

    Reading from File and Storing in Array [HELP]

    Good Evening,

    I'm fairly new to the world of Java programming and have been given an assignment from my university that I'm having trouble with.

    I have to open the file named osaka.dat/txt and take in the information.
    The file contains the times and names (plus some other info) of some Runners, when I have stored the information I will need to be able to sort it and print out the top 3 runners in each section, so being able to arrange things by time would be useful.

    Right now I have some code which I will provide below. With assistance I have been able to get the information to be stored as seperate lines, but the only info that is being stored to an array is the very final set of data, which is a problem since I need all of it and to be able to sort it >.<

    Can anyone help?

    I will post my code and my assignment (also the contents of Osaka.dat) to see if this helps...

    Thanks in advance:

    My Assignment and Osaka.txt

    The txt file: osaka.txt (also saved as a .dat)
    Code:
     Heat 1
      Lane    num   Name                    Nat   Time
       1      334   John Steffensen         AUS   44.82
       2      500   Takeshi Fujiwara        ESA   46.92
       3      651   Dim�trios R�gas         GRE   46.22
       4      352   Chris Brown             BAH   44.5
       5      1050  Rennyuow                TRI   45.7
       6      491   Arismendy Peguero       DOM   44.92
       7      897   Marcin Marciniszyn      POL   45.83
       8      626   Bastian Swillims        GER   45.44
    
     Heat 2
      Lane    num   Name                    Nat   Time
       1      351   Avard Moncur            BAH   45.27
       2      571   Brice Panel             FRA   46.02
       3      1166  Lewis Banda             ZIM   45.47
       4      915   F�lix Mart�nez          PUR   46.86
       5      1151  Jeremy Wariner          USA   45.1
       6      684   David Gillick           IRL   45.35
       7      595   Martyn Rooney           GBR   45.47
       8      846   Herm�n L�pez            NCA   50.72
    
     Heat 3
      Lane    num   Name                    Nat   Time
       1      905   Rafal Wieruszewski      POL   45.94
       2      489   Carlos Santa            DOM   45.99
       3      658   Alleyne Francique       GRN   44.95
       4      1001  Abdulla Mohamed Hussei  SOM   50.54
       5      713   Ricardo Chambers        JAM   45.34
       6      561   Leslie Djhone           FRA   45.17
       7      345   Clemens Zeller          AUT   46.06
       8      596   Andrew Steele           GBR   45.54
    
     Heat 4
      Lane    num   Name                    Nat   Time
       1      349   Andrae Williams         BAH   45.31
       2      1037  Johan Wissman           SWE   44.94
       3      1080  Andr�s Silva            URU   46.79
       4      1120  LaShawn Merritt         USA   44.78
       5      1168  Young Talkmore Nyongan  ZIM   45.4
       6      834   Dalibor Spasovski       MKD   48.63
       7      381   Gakologelwang Masheto   BOT    0.0
       8      842   Eric Milazar            MRI   46.55
    
     Heat 5
      Lane    num   Name                    Nat   Time
       1      584   Timothy Benjamin        GBR   45.44
       2      451   Gary Kikaya             COD   45.21
       3      313   Nicolau Palanca         ANG   48.6
       4      486   Chris Lloyd             DMA   45.46
       5      932   Ioan Lucian Vieru       ROM   46.78
       6      706   Sanjay Ayre             JAM   45.28
       7      954   Vladislav Frolov        RUS   45.69
       8      366   Mathieu Gnaligo         BEN   47.51
    
     Heat 6
      Lane    num   Name                    Nat   Time
       1      708   Michael Blackwood       JAM   45.44
       2      1141  Angelo Taylor           USA   45.13
       3      735   Yuki Yamaguchi          JPN   46.28
       4      380   California Molefe       BOT   45.36
       5      455   Nery Brenes             CRC   45.01
       6      646   Jonathon Lavers         GIB   47.97
       7      999   Ivano Bucci             SMR   48.07
       8      459   William Collazo         CUB   45.29
    
     Heat 7
      Lane    num   Name                    Nat   Time
       1      1049  Ato Modibo              TRI   45.22
       2      891   Daniel Dabrowski        POL   45.5
       3      329   Sean Wroe               AUS   45.39
       4      649   Dim�trios Gr�valos      GRE   46.94
       5      1161  Moses Kamut             VAN   48.9
       6      690   Andrea Barberi          ITA   45.74
       7      1114  Lionel Larry            USA    0.0
       8      425   Tyler Christopher       CAN   45.15
    ...and to save confusion...THIS is my assignment.
    Hopefully it will make more sense than my own ramblings...

    Code:
    ECSC401 Programming Methodology (Java) 
    Semester 1, 2009/10
    Coursework
    Deadline : Tuesday 12th January 2010
    Value : 20 marks
    Requirements
    The results of the mens 400m heats from the 2007 IAAF World Championships in Osaka have been stored in the file osaka.txt. For each heat, the file contains the following information about each athlete: 
    	lane number 
    	competition number {worn on vest} 
    	name 
    	nationality {3 character abbreviation} 
    	time for the race {seconds} 
    The fastest three athletes from each heat automatically qualified for the next round, along with the three overall fastest "losers", so that 24 athletes progressed to the next round of the competition. 
    You are asked to write, in Java :
    	a method to read the data from the file and store it in a suitable way. 
    	a method which lists the fastest three athletes from one heat. 
    	a main method which uses these two methods and establishes which twenty four athletes would progress to the next round of the competition. 
    N.B. It is likely that you will need a few more methods to complete this task. 
    You should hand in the following at the campus office: 
    	A listing of your java program. 
    	A test plan describing the tests that you ran on the program and their results. 
    Please do not include discs! They are not needed thank you. 
    Marks will be lost if you do not follow the Department Coding Standard for code layout.
    My Code:

    Code:
    package coursework1;
    
    import java.lang.*;
    import java.util.*;
    import java.io.*;
    //import java.util.ArrayList;
    //import java.util.List;
    
    
    public class Main {
        //Golbal variables to be accessed by most of my methods
        static String fileName = "";//The file that the user wants to access
        static String [] athlete;//Use as temp Array for data, then move data into a larger arrayList?
          //315 elements
        public static void main (String[] args) throws FileNotFoundException{
        Main.body(args);
               }
    
        private static void body (String[] args) throws FileNotFoundException{
        //the bulk of the code/calling will go here, so that main is left with
        //as few calls as possible for ease.
            Main.getFileName(args);
            Main.readLine(args);
            System.out.println("//////////////////////");
            Main.showAthleteArray(args);
                        }
    
        private static void getFileName (String[] args)throws FileNotFoundException{
            InputStreamReader input = new InputStreamReader(System.in);
            BufferedReader reader = new BufferedReader(input);
            System.out.println("Please type your file name (including the Extension): ");
            // read in user input
            try {
                fileName = reader.readLine();
                }
            catch(Exception e){}
            System.out.println("\n====CONFIRMATION====\nFile Name: " + fileName + "\n==END CONFIRMATION==\n\n");
                }
    
        private static void printFile (String[]args) throws FileNotFoundException{
             //This will Print the file in its entirety.
             try {
                BufferedReader br = new BufferedReader(new FileReader(fileName));
                String strLine;
                while ((strLine = br.readLine()) != null) {
                    System.out.println(strLine);
                }
                br.close();
            } catch (Exception exc) {
                System.err.println("Error: " + exc.getMessage());
            }
        }
    
        private static void readLine (String[] args) throws FileNotFoundException{
           //it reads the lines and then splits them in seperate lines
            try {
                FileInputStream inStream = new FileInputStream(fileName);
                DataInputStream in = new DataInputStream(inStream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String line;
    
                boolean firstHeat = true;
                while ((line = br.readLine()) != null) {
                    if (!line.equals("")) {
                        if (line.trim().startsWith("Heat")) {
                            if (firstHeat) {
                                firstHeat = false;
                            } else {
                                //add old heat to the heat array
                            }
                            //create a new heat object
                        } else {
                            //create new athlete object and add it to the heat
                            athlete = line.trim().split("\\b\\s{2,}\\b");
                            for (int i = 0; i < athlete.length; i++) {
                            //for (int i = 0; i < athlete.length; i++) {
                                //System.out.println(athlete[i]);
                             }
                           }
                    }
                }
                in.close();
            } catch (Exception e) {
                System.err.println("Error: " + e.getMessage());
            }
    
    }
    
        private static void showAthleteArray (String[]args){
            int sum = 0;
            for (int counter = 0; counter < athlete.length; counter++) {
                System.out.println(counter + "\t" + athlete[counter]);
            }
        }
    
    	}

  2. #2
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Reading from File and Storing in Array [HELP]

    Your athlete array holds the data for a single line, i.e. the fields for a single athlete. Each time round the loop you assign it the next athlete. At the end, it hold the data for the last athlete.

    If you want to store the data for every athlete, you need to have a list of athlete arrays, one array for each athlete. Or maybe you only want to store certain athletes... whatever, I didn't read the assignment.

    Incidentally, your code checks for a 'Heat' line, but it doesn't check for the following header line (with the column headings), and treats it like an athlete...

    It would probably help if you decided exactly what your code needs to do before trying to write any Java. What steps do you need to do, what data do you need to store at each step? Try writing it all down on paper in English and stepping through until you're satisfied you know exactly how to solve the problem. Then you can try to translate it into Java. The real key to programming is to solve the problem in logical steps. Writing code in a particular language is just a way of expressing that solution. There's no point trying to write code until you know exactly what it needs to do.

    The best writing is rewriting...
    E. B. White
    Please use &#91;CODE]...your code here...&#91;/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  3. #3
    Join Date
    Jan 2010
    Posts
    3

    Re: Reading from File and Storing in Array [HELP]

    Quote Originally Posted by dlorde View Post
    Your athlete array holds the data for a single line, i.e. the fields for a single athlete. Each time round the loop you assign it the next athlete. At the end, it hold the data for the last athlete.

    If you want to store the data for every athlete, you need to have a list of athlete arrays, one array for each athlete. Or maybe you only want to store certain athletes... whatever, I didn't read the assignm...
    Hi thanks for your reply ^^
    I was thinking along the lines of using a 2D array, one array to hold all the athlete arrays...
    However when I attempt to implement this I always seem to fall flat on my face with it >.<

    Do you have any suggestions as to how I can implement it into my code?

    Code:
    private static void readLine (String[] args) throws FileNotFoundException{
           //it reads the lines and then splits them in seperate lines
            try {
                FileInputStream inStream = new FileInputStream(fileName);
                DataInputStream in = new DataInputStream(inStream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String line;
    
                boolean firstHeat = true;
                while ((line = br.readLine()) != null) {
                    if (!line.equals("")) {
                        if (line.trim().startsWith("Heat")) {
                            if (firstHeat) {
                                firstHeat = false;
                            } else {
                                //add old heat to the heat array
                            }
                            //create a new heat object
                        } else {
                            //create new athlete object and add it to the heat
                            athlete = line.trim().split("\\b\\s{2,}\\b");
                            for (int i = 0; i < athlete.length; i++) {
                            //for (int i = 0; i < athlete.length; i++) {
                                //System.out.println(athlete[i]);
                             }
                           }
                    }
                }
                in.close();
            } catch (Exception e) {
                System.err.println("Error: " + e.getMessage());
            }
    
    }
    I feel that even if I had one large array holding all the athletes I could still sort them by the Time and print out the Winners...its just the Storage that's stumping me >.<

    Im still working on the code with others, I have written a psudocode but sadly because I am so new to all this i'm held back by what I know (or don't know) lol

    Thanks for anyhelp

  4. #4
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Reading from File and Storing in Array [HELP]

    Arrays are fixed-length storage. It makes sense to use an array for storing the data for an athlete because you know exactly how many items there are. However, you don't know how many athletes may be in the file, so an array to hold all the athletes is not such a good idea, because you don't know how big to make it. In this situation, you want dynamic storage, such as a List, e.g. ArrayList.

    You can sort a List using Collections.sort(..). By default this will sort by the 'natural order' of the items stored, which means the items need to implement the Comparable interface - but since an array can't implement interfaces, you'll need to use the Collections.sort method that takes a separate Comparator object that can compare two athlete arrays.

    Alternatively, you could make an Athlete class with fields for the data instead of using an array for athlete, and have it implement Comparable.

    If you have some specific problem translating your pseudocode to Java, post the pseudocode and your translation so far, and describe the problem.

    Come to think of it, there are already a million monkeys on a million typewriters, and Usenet is nothing like Shakespeare...
    Blair Houghton
    Please use &#91;CODE]...your code here...&#91;/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  5. #5
    Join Date
    Jan 2010
    Posts
    3

    Re: Reading from File and Storing in Array [HELP]

    Hi thanks for your help ^^

    I'm trying to use an ArrayList now, however, I think I have been able to get it to store the Athlete Arrays however, it is storing it as a very odd value...

    Code:
        private static void readLine (String[] args) throws FileNotFoundException{
           //it reads the lines and then splits them in seperate lines
            try {
                FileInputStream inStream = new FileInputStream(fileName);
                DataInputStream in = new DataInputStream(inStream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String line;
            
                boolean firstHeat = true;
                while ((line = br.readLine()) != null) {
                    if (!line.equals("")) {
                        if (line.trim().startsWith("Heat")) {
                            if (firstHeat) {
                                firstHeat = false;
                            } else {
                                //add old heat to the heat array
                            }
                            //create a new heat object
                        } else {
    
                            //create new athlete object and add it to the heat
                            athlete = line.trim().split("\\b\\s{2,}\\b");
                            for (int i = 0; i < athlete.length; i++) {
                            //for (int i = 0; i < athlete.length; i++) {
                                //System.out.println(athlete[i]);
                                heatsL.add(athlete);
                            }
                           }
                    }
                }
                in.close();
                } catch (Exception e) {
                System.err.println("Error: " + e.getMessage());
            }
              Object HeatsArray[] = heatsL.toArray();
    
              int sum = 0;
            System.out.println("Contents of Athlete Array");
            for (int counter = 0; counter < HeatsArray.length; counter++) {
                System.out.println(counter + "\t" + HeatsArray[counter]);
    
    
            }
    
    }
    I keep getting this type of value, rather than the actual Strings O_o

    Code:
    [[Ljava.lang.String;@1034bb5, [Ljava.lang.String;@1034bb5, [Ljava.lang.String;@1034bb5, [Ljava.lang.Stri...etc
    Right now, I tried converting my ArrayList to an array, believing that it would solve the problem, but it didnt >< Any ideas as to why it is storing those values?
    Can someone put me out of my misery with this lol!

  6. #6
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Reading from File and Storing in Array [HELP]

    It isn't storing those values, it is printing those values. An array is just an object that contains a sequence of other objects. The runtime doesn't know how you want it printed out, so it uses the default toString() method supplied for all objects, which is to print out its class name and its hashcode (see Object.toString()).

    For true classes, you can override the toString() method and provide your own implementation, but not for arrays, which aren't true classes. If you want the contents of the array printed out, you need to print each element separately.

    Think twice, code once...
    Anon.
    Please use &#91;CODE]...your code here...&#91;/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center