Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 45

Thread: Problems with File Reader (Strings and 2D Array Storage)

  1. #1
    Junior Member
    Join Date
    Dec 2009
    Posts
    24
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Red face Problems with File Reader (Strings and 2D Array Storage)

    Okay. I apologise if this is in the wrong section ^^

    The assignment that I have been given asks me to use a .txt file (that contains 7 heats, each with 8 runners with their times, nationalities, numbers etc) and read it contents, I have to take the various values (names, times, nationalities etc) and store them suitably in an Array. I then have to present a way to print out the data in particular order...ie. Runners who have the fastest time.

    This may sound odd and I would like to clarify that I do NOT want this 'completed for me'.
    All I require are the tools so I can do it myself ^^

    My tutor was very vague in regards to using the FileReader and I'm having trouble getting it to work.
    I can't seem to work it out, not only that but I need to store Ints, Floats and Strings.

    My plan is to store all the standard info (name, nat, etc) as Strings in a 2-D array.
    ie. Array [1][7] will give me the info for the first heat and runner number 7 (I'm ignoring array 0 for ease of access).

    But, to help do this, when I ever get the FileReader to work I will also need to be able to skip over values in the .txt file so that I am able to store their Race Times in a separate array of doubles.

    Follow me so far?

    Okay, well, I guess I'll post up my code...its 'bitty' atm, but I'd ask you to direct your attention to the class times, thats where I'm working first of all (to get used to FileReader I'll work on storing the TIMEs as doubles to begin with)

    Please be gentle with me -- I've only be studying this for a few months ^^
    package coursework1;
     
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.util.Scanner;
     
    public class Main {
     
        public static void main(String[] args) throws FileNotFoundException {
            //TO DO///////////////////////////////////
            //READ IN DATA and STORE                //
            //PRINT DATA                            //
            //PRINT Fastest 3 Runners from Each Heat//
            //////////////////////////////////////////
            Main.times(args);
     
    //        FileReader frName = new FileReader("osaka.dat");
    //        Scanner infile = new Scanner (frName);
    //
    //        String test = infile.nextLine();
    //        System.out.println(test);
    //        infile.close();
     
        }
     
        public static void athlete(String[] args) throws FileNotFoundException {
     
            String[][] HeatNfo = new String[8][9];
     
    //        FileReader frName = new FileReader("osaka.txt");
    //        Scanner infile = new Scanner (frName);
    //
    //        String test = infile.nextLine();
    //        System.out.println("Test");
    //        infile.close();
     
        }
     
        public static void times(String[] args) throws FileNotFoundException {
            //Read in times and store them in an array
            int[][] HeatTime = new int[8][9];
     
            FileReader frTime = new FileReader("osaka.txt");
            Scanner infile = new Scanner(frTime);
     
            for (int counter = 0; counter < 25; counter++) {
                //infile.skip(long n);
                HeatTime[0][counter] = infile.nextInt();
     
     
     
            }
            infile.close();
     
     
        }
     
        {//Array of Strings.
    //First array postion will store the heats.
    //The next array within this will store the racers within the heats.
    //The third directory in the array will store the racers info in this order:
    //Lane, Num, Name and Nat.
    //For example: [2][7][3] will return Heat 2, Racer 7, Name (Martyn Rooney)
    //I will store the times in another class seperatly as Doubles.
        }
     
        public static void display(int x[][]) {
            for (int row = 0; row < x.length; row++) {
                for (int column = 0; column < x[row].length; column++) {
                    System.out.print(x[row][column] + "\t");
                }
                System.out.println();
     
            }
        }
        //This will display all results in a 2-D Array
    }
    The txt file: osaka.txt (also saved as a .dat)
     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...

    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. 
     
    You should also email the java source code to your tutor: 
    •	Cavendish Chris Bailey 
    •	Harrow Artie Basukoski

    Thanks in advance for any help and advice


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    Review your use of the Scanner object; it will be necessary to read in all sorts of data: int's, Strings, floats, etc...you know their order based upon the file format that you have so you can utilize the appropriate Scanner methods in the appropriate order to retrieve the data (see Scanner (Java 2 Platform SE 5.0)). Further, rather than writing a deterministic approach to reading the file (aka a method that reads only a single file with the same length and identical format), I'd say its good practice to step back a second a jot down a general file format and use this as the basis for how you read the file (for example, what if you wish to read more than one file and you do not know how many heats it has, or how many competitors there are in each heat?). This may be more advanced than the assignment is asking, but doing it this way will allow your method to read not just one file, but many - the more adaptable the format you lay out the better it will be for reading different types of files.
    As far as storage, because Java is object oriented perhaps a more ordered and readable method to place the data into memory would be to create objects - say a class Competitor and a class Heat, and store them in some sort of array.

  3. The Following 2 Users Say Thank You to copeg For This Useful Post:

    JavaPF (January 4th, 2010), K0209 (January 5th, 2010)

  4. #3
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    Moved to File I/O & Other I/O Streams - Java Programming Forums

    Anything to do with reading files, taking user input from the console etc goes there.
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  5. #4
    Junior Member
    Join Date
    Dec 2009
    Posts
    24
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    @copeg thanks for such a detailed reply ^^
    Hm you do have a point. It would be far better practice to design code that would be able to accept files of different names and with different number of heats, these variables could easily be taken from User Input. I still can't get the File Reader code to work and actually store anything ¬_¬; I really can't see what I'm doing wrong.

  6. #5
    Junior Member
    Join Date
    Jan 2010
    Posts
    18
    Thanks
    0
    Thanked 3 Times in 2 Posts

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    Hey
    Did your teacher specifically say that you have to use the Scanner method?
    The easier way would be to do this:
     {
        public static void main(String args[])
        {
            try 
            {
                BufferedReader br = new BufferedReader( new FileReader( "osaka.dat" ) );
                String strLine;
                while ((strLine = br.readLine()) != null)
                {
                     System.out.println (strLine);
                }
                br.close();
            }
            catch (Exception exc)
            {
                System.err.println("Error: " + exc.getMessage());
            }
        }
    }

    This way you would be able to read the file and then also put them into 2D arrays.

    Another option would be to use this :
    public static void main(String[] args) throws IOException
    	{
     
    Scanner scanner = new Scanner(new File("osaka.dat"));
     
     
    while (scanner.hasNext())
    {
     
    	System.out.println(scanner.nextLine());
    	}
    	}
    That way you would use the Scanner method and be able to read everything
    Last edited by teen-omar; January 5th, 2010 at 05:18 PM.

  7. The Following 2 Users Say Thank You to teen-omar For This Useful Post:

    K0209 (January 6th, 2010), nasi (May 6th, 2010)

  8. #6
    Junior Member
    Join Date
    Dec 2009
    Posts
    24
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    @teen-omar; no I wasn't told to specifically use the Scanner method and the code you have shown me is VERY useful for reading an ENTIRE document, but alas, my requirements are quite specific.

    I have written some more code to gather the simplest of variables that are associated with the task at hand:
    -File Name
    -Number of Heats
    -Number of Competitors per Heat

    My method asks the user for input via the command line and confirms their inputs once they have provided all the requested information.

    I was attempting to gather the Runners times, but for some reason it wouldn't allow me to read in doubles into an array O_o

    This seems to be my biggest hurdle, getting the specific info and putting it in the right/appropriate place...once I have worked that out I'll be on easy street lol

    package coursework1;
     
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.InputStreamReader;
    import java.util.Scanner;
     
    public class Main2 {
     
        public static void main(String[] args) throws FileNotFoundException {
            int noOfHeats = 0;
            int noOfCompet = 0;
            int nameNoEx = 0;
     
            String fileName = "";
            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("You typed: " + fileName + "\n");
     
    ////////////////////////////////////////////////////////////////////////////////
     
            System.out.println("Please enter the number of heats: ");
            Scanner input1 = new Scanner(System.in);
            noOfHeats = input1.nextInt();
     
    ////////////////////////////////////////////////////////////////////////////////
     
            System.out.println("Please enter the number of Competitors PER HEAT: ");
            Scanner input2 = new Scanner(System.in);
            noOfCompet = input2.nextInt();
     
    ////////////////////////////////////////////////////////////////////////////////
     
            System.out.println("\n==CONFIRMATION==\nFile Name: " + fileName + "\nNo. Heats: " +
                    noOfHeats +  "\nNo. Competitors per Heat: "
                    + noOfCompet + "\n==END CONFIRMATION==\n\n");
     
    ////////////////////////////////////////////////////////////////////////////////
            //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());
    //        }
     
        }
     
         public static void display(int x[][]) {
            for (int row = 0; row < x.length; row++) {
                for (int column = 0; column < x[row].length; column++) {
                    System.out.print(x[row][column] + "\t");
                }
                System.out.println();
     
            }
        }
    }

    and this is my 'broken' code for trying to read in doubles...its ... uh, complicated, but I coulda' sworn that I had it written correctly...

    public static void times(String[] args) throws FileNotFoundException {
            //Read in times and store them in an array as Doubles
            double[][] heatTime = new double[8][9];
            int heatNo = 1;
            FileReader frTime = new FileReader("osaka.dat");
            Scanner ifTimes = new Scanner(frTime);
     
            for (int counter = 0; counter <= 8; counter++) {
                heatTime[heatNo][counter] = ifTimes.nextDouble();
                System.out.print(heatTime[heatNo][counter] + "\n");
                heatNo++;
             while (heatNo < 8 ){
     
             }
                heatNo = 1;
     
            }
            ifTimes.close();
     
     
        }

    Thank you all for your help so far -- I'm already learning so much from you all and this magnificent forum!! ^_^

    EDIT: Also, I've tried Google mercilessly for this...but, if I set a variable say...VARI1, and I want to use that variable in another method outside of the one where it was initalised...is there a wayto use it? Or do I need to find another way? I would much prefer to avoid using Global Variables... thanks.
    Last edited by K0209; January 6th, 2010 at 08:23 AM.

  9. #7
    Junior Member
    Join Date
    Jan 2010
    Posts
    18
    Thanks
    0
    Thanked 3 Times in 2 Posts

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    Hey
    I am not fully sure why you are going to ask the user to enter the number of heats and athletes, because even if they enter wrong values in, the reader will still display the full text.
    I think this could lead to a bug at a later stage or so, but I'm not sure myself.

  10. #8
    Junior Member
    Join Date
    Dec 2009
    Posts
    24
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    Quote Originally Posted by teen-omar View Post
    Hey
    I am not fully sure why you are going to ask the user to enter the number of heats and athletes, because even if they enter wrong values in, the reader will still display the full text.
    I think this could lead to a bug at a later stage or so, but I'm not sure myself.
    My intention is to produce a program that can read in a file with more than the standard heats and nos of athletes and print out the 'winners' from each heat.

    As I mentioned, as useful as the code was that you provided, I need to read in the data more specifically and store it all in suitable arrays so that I can print it out in an order or at request.

    Printing the ENTIRE document, while useful, doesn't help me very much with this assignment as a whole.

    Thanks anyway

  11. #9
    Junior Member
    Join Date
    Dec 2009
    Posts
    24
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    Apologies for double posting... I'm making some head way with the program...
    However still having trouble getting and storing doubles (and data in general ¬_¬

    Heres the newest code...

    package coursework1;
     
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Scanner;
     
    public class Main2 {
            static String fileName = "";
            static int noOfHeats = 0;
            static int noOfCompet = 0;
            static int nameNoEx = 0;
            static int totalCompet = noOfCompet * noOfHeats;
            static double [] heatTimes = new double [totalCompet];
     
        public static void main (String[] args) throws FileNotFoundException{
        Main2.body(args);
        Main2.readTimes(args);
        }
     
        private static void body (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("Please enter the number of heats: ");
            Scanner input1 = new Scanner(System.in);
            noOfHeats = input1.nextInt();
     
    ////////////////////////////////////////////////////////////////////////////////
     
            System.out.println("Please enter the number of Competitors PER HEAT: ");
            Scanner input2 = new Scanner(System.in);
            noOfCompet = input2.nextInt();
     
    ////////////////////////////////////////////////////////////////////////////////
     
            System.out.println("\n==CONFIRMATION==\nFile Name: " + fileName + "\nNo. Heats: " +
                    noOfHeats +  "\nNo. Competitors per Heat: "
                    + noOfCompet + "\n==END CONFIRMATION==\n\n");
     
    ////////////////////////////////////////////////////////////////////////////////
            //This will Print the file in its entirety. I will keep it here should I need it
    //        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());
    //        }
     
        }
     
        [B]private static void readTimes(String[]args) {
            //Buffered Reader to readLine(), then parse into Double
        for (int counter = 0; counter < heatTimes.length; counter++){
                try {
                BufferedReader reader = new BufferedReader(new FileReader(fileName));
                String input = reader.readLine();
     
                double number = Double.parseDouble(input);
                heatTimes[counter]=number;
                System.out.print(heatTimes[counter] + "/n");
                reader.close();
     
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    Main2.displayHeatTimes(args);
        }[/B]
     
        private static void display2d(int x[][]) {
            for (int row = 0; row < x.length; row++) {
                for (int column = 0; column < x[row].length; column++) {
                    System.out.print(x[row][column] + "\t");
                }
                System.out.println();
     
            }
        }
     
        private static void displayHeatTimes(String[] args){
            //a method to display the values in heatTimes array
            int sum = 0;
    for (int counter =0; counter<heatTimes.length; counter++){
    sum += heatTimes[counter];
    System.out.println(counter + "\t" + heatTimes[counter]);
    }
        }
     
    }

    I'm currently working on "private static void readTimes(String[]args)" , when I run the program as it is currently this method seems to do 'nothing'. Can anyone see something I can't. Okay, that's a stupid question since everyone on here is a hellava lot better at this than me .. I'm trying though!!

    Thanks.

  12. #10
    Junior Member
    Join Date
    Jan 2010
    Posts
    18
    Thanks
    0
    Thanked 3 Times in 2 Posts

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    Hey
    Are there any other classes you have created for which the code isn't displayed?
    Because this might give us a clue as to what to do next.
    Been looking at your code, and the display2d method isn't doing anything at the moment.
    If you can, put up the rest of the codes so that we can have a further look.

  13. #11
    Junior Member
    Join Date
    Dec 2009
    Posts
    24
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    ^Actually that's the whole code.
    I originally intended to use 2 Dimensional Arrays to store my info, and that code would've showed all the values in a 2D array.
    I kept it there as reference for the time being, just incase I reverted back to using 2D arrays. (But I have got to store stuff first lol).

    So yeah, that's the whole code currently, ignore display2d if it helps, as you say it does nothing and there are no other methods or classes involved yet.

    My current dilemma is situated in readTimes (in BOLD)...hope that helps!
    Thanks

  14. #12
    Junior Member
    Join Date
    Jan 2010
    Posts
    18
    Thanks
    0
    Thanked 3 Times in 2 Posts

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    With your code, have you tested whether it saves the Heat times into array? made any checks like "System.out.print..."
    Always make sure that the Array works in terms of storing the data
    So are you saying that you're not intending to use the 2D array now or what is the case?
    Been looking through your code now for more than 1/2 hour and still can't seem to fint eh missing puzzle piece....
    I'll update you on anything new ;-)

  15. #13
    Junior Member
    Join Date
    Dec 2009
    Posts
    24
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    At the end of readTimes I called the method "Main2.displayHeatTimes(args);", this is a simple method that displays the all values in an array. Its worked on the dozens of other programs I have made which have used arrays and alas, it just seems to do 'nothing' O_o

    I really appreciate the help, thank you very very much

  16. #14
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    In reference to readTimes in its current form: you are going to need a method that is more elaborate than that, because you cannot just parse a double out of the line. You can split up the line based upon spaces and then parse the information out from that. Look at the API for String, which gives you several ways to deal with strings (in particular look at the split method to break up as string on whitespace, the trim() method to trim any whitespace on the ends of a String, the length method to see if it is just an empty string, and perhaps the indexOf method to search for whether the line begins with "Heat" or "Lane" as opposed to an actual competitor). An example of an algorithm would be to see if the line is empty, if it is not check to see if it begins with Heat, if it does get the heat number, if not check to see if it begins with Lane, if it does not split the line (based upon whitespace) into an array, then parse each array element in the appropriate form (int, double, etc...). A good algorithm will take into account file formats that are written inappropriately (eg a split does not give you the appropriate sized array)

    Teen-omar has a good point: it shouldn't be necessary for the user to have to enter the number of heats/competitors in the file: the file specifies it already you just need to read it in the right way (just allocate the memory dynamically (for example an ArrayList object))

    Here's a more specific breakdown of the problem (at least as I see it and laid out in a previous post)

    Draw the file format in an abstract way , something like this (brackets indicate a repetitive element which can be repeated x times)
    [Heat n
    "Lane    num   Name     Nat   Time"
    [int    int   String     String   double] x times
    ] x times
    [blank line] zero or more times

    When you see a file format like this with things repeated x times, it should be screaming out use objects.

    Either way, as you read each line remember that readLine() returns the entire line, so it will contain all the data on that line...since you know the format, check if its a Heat or a competitor line and split the line up into elements (See String.split()) to retrieve the data.
    Last edited by copeg; January 6th, 2010 at 07:20 PM.

  17. The Following User Says Thank You to copeg For This Useful Post:

    K0209 (January 6th, 2010)

  18. #15
    Junior Member
    Join Date
    Dec 2009
    Posts
    24
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    ^I really like that idea. Sadly, my own knowledge is kinda holding me back here... I have changed my code and feel this time (finally) that I am on the right track... I have put in BOLD the area which needs attention. I am trying to read in, split and store the String, but I am still having trouble getting this to work.

    Can anyone provide any examples? Or links to examples?

    This is a bit beyond me I feel, but my work is due next week and I know once I have nailed the input, I'll be alright >.<

    package coursework1;
     
    import java.lang.*;
    import java.util.*;
    import java.io.*;
     
    public class Main {
        //Golbal variables to be accessed by most of my methods
        static String fileName = "";//The file that the user wants to access
     
        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.readLineIn(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());
            }
        }
     
        [B]private static void readLineIn (String[]args) throws FileNotFoundException {
            //Buffered Reader to readLine()
            FileReader lineIn = new FileReader(fileName);
            BufferedReader reader = new BufferedReader(lineIn);
            try {
                fileName = reader.readLine();
                }
            catch(Exception e){}
            Main.dump(args);
                    }
     
        private static void dump(String []s) {
        System.out.println("------------");
        for (int i = 0 ; i < s.length ; i++) {
            System.out.println(s[i]);
        }
        System.out.println("------------");
      }[/B]
     
     
     
    }

    Thank you for all your help so far ^^

    Also, if it helps, my tutor provided us with this code he made in the last lecture, and posted it a few days ago...he says it has everything we need. I have looked at it and taken it apart but really can't see how O_o

    Maybe it will help here:

    package lecture10;
     
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Scanner;
     
    /**
     *
     * @author Artie
     */
    public class AccountsArray {
     
        static final int ACC_MAX = 1000;
     
        private static int readAccounts(Account[] accs) {
            //Create a file reader for accounts.dat
            Scanner infile = null;
            try {
                FileReader fr = new FileReader("accounts.dat");
                infile = new Scanner(fr);
            } catch (IOException exc) {
                System.out.println("File not found " + exc);
            }
     
            int nRead = 0;
     
            //read the file
            while (infile.hasNext() && (nRead < ACC_MAX)) {
                int aNum = infile.nextInt();
                double aBal = infile.nextDouble();
                accs[nRead] = new Account(aNum, aBal);
                nRead++;
            }
            infile.close();
            System.out.println(nRead + " accounts read\n");
            return nRead;
        }
     
        private static void writeAccounts(Account[] accs, int length) throws FileNotFoundException {
            PrintWriter opf = new PrintWriter("accountsOut.dat");
            for (int i = 0; i < length; i++) {
                opf.println(accs[i].getAccno() + " " + accs[i].getBalance());
            }
            opf.close();
            System.out.println(length + " accounts written\n");
        }
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) throws FileNotFoundException {
            Account[] accs = new Account[ACC_MAX];
            int nRead = readAccounts(accs);
            writeAccounts(accs, nRead);
        }
    }

    Thanks

    EDIT: New readLineIn.... Ithink I'm getting closer...just need to be able to store these in arrays >.<

    private static void readLineIn (String[]args) throws FileNotFoundException {
            //Buffered Reader to readLine()
            BufferedReader reader = new BufferedReader(new FileReader(fileName));
            try {
                while (reader.ready()) {
                    for (String field : reader.readLine().split(" ")) {
                        // do whatever
                        System.out.println(field);
                    }
                }
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
                    }

    Also, is there any way on this forum to use Spoiler tags? To hide big bits of text and code that may not be useful? ie. that bit my tutor provided? Sure its useful, but it would be nice to hide it lol
    Last edited by K0209; January 7th, 2010 at 09:05 AM.

  19. #16
    Junior Member
    Join Date
    Jan 2010
    Posts
    18
    Thanks
    0
    Thanked 3 Times in 2 Posts

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    hey k0209, any chance of uploading the account.dat file so we can check out the way he laid it out in the file?
    Also, i think you forgot to post up a separate class file which holds the information of how to access the methods.
    So that, so we can have a further look.
    BTW, are you 100% sure your teacher said that this is all you need to complete your assignment???
    Because I'm not seeing any BufferedReader so i'm kind of wondering right now.....hmmmm

  20. #17
    Junior Member
    Join Date
    Dec 2009
    Posts
    24
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    ^All he provided was the above... plus, he said "play with it". So he's either encouraging self discovery or for us to modify the code lol

    I think...(THINK) i'm getting there, if I count the spaces between the sections I can assign them to an array list as necessary....i think...

    Any ideas?

    EDIT: Maybe not, since the distance between num and name isn't always the same >.< lol

    EDIT 1.2: Okay, heres what I have... so far, this bit of code takes the file and splits it into lines...
    private static void readLineIn (String[]args) throws FileNotFoundException {
            //Buffered Reader to readLine()
            BufferedReader reader = new BufferedReader(new FileReader(fileName));
            try {
                while (reader.ready()) {
                    for (String field : reader.readLine().split([B]"\n"[/B])) {
                        // do whatever
                        System.out.println(field);
                    }
                }
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
                    }

    Now, all I need to do is split those lines into their relevant data types and store them in an array or array List...
    Last edited by K0209; January 7th, 2010 at 09:18 AM.

  21. #18
    Junior Member
    Join Date
    Jan 2010
    Posts
    18
    Thanks
    0
    Thanked 3 Times in 2 Posts

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    The distance between num and name isn't always same, but it is always greater than 2, so elaborate on that ;-)
    but between Nat and time there are always 3 spaces, so have you taken that into consideration (sorry if you already have)

  22. #19
    Junior Member
    Join Date
    Dec 2009
    Posts
    24
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    I have tried, do you think the method mentioned in my above edit 1.2 is a good way to go?

  23. #20
    Junior Member
    Join Date
    Jan 2010
    Posts
    18
    Thanks
    0
    Thanked 3 Times in 2 Posts

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    lol, seems like you want to experiment a lot with the java classes.
    how come you are jusing the Logger class now?
    If you want to split up the data, you could use a .trim for it.
    Here is a code i quickly made for your task, what it does it reads the lines and then splits them in seperate lines
    hope this should help you immensely ;-)
    try 
    		{
    			FileInputStream inStream = new FileInputStream("osaka.txt");
    			DataInputStream in = new DataInputStream(inStream);
    			BufferedReader br = new BufferedReader(new InputStreamReader(in));
    			String line;
     
    			// create an array of heats for size 7
    			// Heat[] heats = new Heat[7];
    			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
    						String [] lol = line.trim().split("\\b\\s{2,}\\b");
    						for (int i=0; i < lol.length; i++)
    						{
    							System.out.println(lol [i]);
    						}
    						System.out.println(line);
    					}
     
    				}
     
    			}
     
    			in.close();
    		} 
    		catch (Exception e) 
    		{
    			System.err.println("Error: " + e.getMessage());
    		}
    	}
    }

  24. The Following User Says Thank You to teen-omar For This Useful Post:

    K0209 (January 7th, 2010)

  25. #21
    Junior Member
    Join Date
    Dec 2009
    Posts
    24
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    Wow! You wrote that?!
    I wish I had that kinda know how here! ^__^

    If I'm honest, I love programming! I want to know all there is to it, but since I've only been studying for a short while I'm held back by 'what I actually know' lol

    That code you provided looks perfect! I'll implement it and see how it goes lol

    This is what I came up with before your reply ^^
    It stores each line in a different postion in a ArrayList.
    If I could work out how to split/store them from there i'd be on easy street lol

    Thank you so much for your help!

        private static void readLineIn (String[]args) throws FileNotFoundException {
            //Buffered Reader to readLine()
            BufferedReader reader = new BufferedReader(new FileReader(fileName));
            try {
                while (reader.ready()) {
                    for (String field : reader.readLine().split("\n")) {
                        // do whatever
                        list.add(field);
                       }
                }
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println(list);
                    }

  26. #22
    Junior Member
    Join Date
    Jan 2010
    Posts
    18
    Thanks
    0
    Thanked 3 Times in 2 Posts

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    Let me know when your code is perfected, would love to see how it ends up as ;-)
    BTW, the code you posted, i don't seem to understand where you got the "list" from.
    Make sure you initialize if first before you use it
    Last edited by teen-omar; January 7th, 2010 at 09:43 AM.

  27. #23
    Junior Member
    Join Date
    Dec 2009
    Posts
    24
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    Quote Originally Posted by teen-omar View Post
    Let me know when your code is perfected, would love to see how it ends up as ;-)
    BTW, the code you posted, i don't seem to understand where you got the "list" from.
    Make sure you initialize if first before you use it
    Naturally!
    Although I'd bet I'll be back for help before the end of the day! lol

  28. #24
    Junior Member
    Join Date
    Dec 2009
    Posts
    24
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    Its probably just me being dense, but I can't seem to fit this into my code.
    While I have been able to call it, I'm a bit at a loss as to how I go about retrieving the various values and also to start arranging them lol

    Sorry, I feel like such a dunce!

    package coursework1;
     
    import java.lang.*;
    import java.util.*;
    import java.util.logging.*;
    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 List list = new ArrayList();
        static List newList = new ArrayList();
     
        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.readLineInv1(args);
            Main.readLineInv2(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 readLineInv1 (String[]args) throws FileNotFoundException {
            //Buffered Reader to readLine() then stores in Array List
            BufferedReader reader = new BufferedReader(new FileReader(fileName));
            try {
                while (reader.ready()) {
                    for (String field : reader.readLine().split("\n")) {
                        // do whatever
                        list.add(field);
     
                       }
                }
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println(list);
            System.out.println("------------");
                    }
     
       [B] private static void readLineInv2 (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;
     
                // create an array of heats for size 7
                //Heat[] heats = new Heat[7];
                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
                            String[] lol = line.trim().split("\\b\\s{2,}\\b");
                            for (int i = 0; i < lol.length; i++) {
                                System.out.println(lol[i]);
                            }
                            System.out.println(line);
                        }
     
                    }
     
                }
                in.close();
            } catch (Exception e) {
                System.err.println("Error: " + e.getMessage());
            }
     
    }[/B]
     
     
    	}

  29. #25
    Junior Member
    Join Date
    Jan 2010
    Posts
    18
    Thanks
    0
    Thanked 3 Times in 2 Posts

    Default Re: Problems with File Reader (Strings and 2D Array Storage)

    here's the thing
    you are trying to use your reading in method, along with the one i provided
    use the one i gave you, and build on it the arrays and stuff you gotta do
    so get rid of your reading in method of the file and work from there ;-)

Page 1 of 2 12 LastLast

Similar Threads

  1. Buffered Reader is not reading my file properly... HELP!
    By mannyT in forum File I/O & Other I/O Streams
    Replies: 8
    Last Post: November 8th, 2009, 08:14 PM
  2. Strings
    By Leeds_Champion in forum Algorithms & Recursion
    Replies: 3
    Last Post: November 3rd, 2009, 10:09 PM
  3. greetings and a file reader problem
    By chileshe in forum File I/O & Other I/O Streams
    Replies: 0
    Last Post: October 6th, 2009, 03:45 AM
  4. Returning Random Strings from an Array
    By cfmonster in forum Collections and Generics
    Replies: 3
    Last Post: September 8th, 2009, 11:13 PM
  5. Code to read a character in the file
    By Truffy in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: May 19th, 2009, 06:11 PM