Go Back   Java Programming Forums > Java Standard Edition Programming Help > File I/O & Other I/O Streams


Reply
 
LinkBack Thread Tools Display Modes
  #11 (permalink)  
Old 06-01-2010, 10:33 PM
Junior Member
 

Join Date: Dec 2009
Posts: 24
Thanks: 4
Thanked 0 Times in 0 Posts
K0209 is on a distinguished road

I'm feeling Lurking
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



Reply With Quote
Sponsored Links
Java Training from DevelopIntelligence
  #12 (permalink)  
Old 06-01-2010, 10:58 PM
Junior Member
 

Join Date: Jan 2010
Posts: 18
Thanks: 0
Thanked 3 Times in 2 Posts
teen-omar is on a distinguished road
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 ;-)
Reply With Quote
  #13 (permalink)  
Old 06-01-2010, 11:01 PM
Junior Member
 

Join Date: Dec 2009
Posts: 24
Thanks: 4
Thanked 0 Times in 0 Posts
K0209 is on a distinguished road

I'm feeling Lurking
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
Reply With Quote
  #14 (permalink)  
Old 06-01-2010, 11:16 PM
copeg's Avatar
Moderator
 
9 Highscores

Join Date: Oct 2009
Posts: 570
Thanks: 7
Thanked 131 Times in 125 Posts
copeg will become famous soon enoughcopeg will become famous soon enough

I'm feeling Sleepy
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)
Java Code
[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; 06-01-2010 at 11:20 PM.
Reply With Quote
The Following User Says Thank You to copeg For This Useful Post:
K0209 (06-01-2010)
  #15 (permalink)  
Old 07-01-2010, 12:47 PM
Junior Member
 

Join Date: Dec 2009
Posts: 24
Thanks: 4
Thanked 0 Times in 0 Posts
K0209 is on a distinguished road

I'm feeling Lurking
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 >.<

Java Code
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());
        }
    }

    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("------------");
  }



}
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:

Java Code
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 >.<

Java Code
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; 07-01-2010 at 01:05 PM.
Reply With Quote
  #16 (permalink)  
Old 07-01-2010, 01:04 PM
Junior Member
 

Join Date: Jan 2010
Posts: 18
Thanks: 0
Thanked 3 Times in 2 Posts
teen-omar is on a distinguished road
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
Reply With Quote
  #17 (permalink)  
Old 07-01-2010, 01:09 PM
Junior Member
 

Join Date: Dec 2009
Posts: 24
Thanks: 4
Thanked 0 Times in 0 Posts
K0209 is on a distinguished road

I'm feeling Lurking
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...
Java Code
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
                    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; 07-01-2010 at 01:18 PM.
Reply With Quote
  #18 (permalink)  
Old 07-01-2010, 01:16 PM
Junior Member
 

Join Date: Jan 2010
Posts: 18
Thanks: 0
Thanked 3 Times in 2 Posts
teen-omar is on a distinguished road
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)
Reply With Quote
  #19 (permalink)  
Old 07-01-2010, 01:20 PM
Junior Member
 

Join Date: Dec 2009
Posts: 24
Thanks: 4
Thanked 0 Times in 0 Posts
K0209 is on a distinguished road

I'm feeling Lurking
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?
Reply With Quote
  #20 (permalink)  
Old 07-01-2010, 01:27 PM
Junior Member
 

Join Date: Jan 2010
Posts: 18
Thanks: 0
Thanked 3 Times in 2 Posts
teen-omar is on a distinguished road
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 ;-)
Java Code
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());
		}
	}
}
Reply With Quote
The Following User Says Thank You to teen-omar For This Useful Post:
K0209 (07-01-2010)
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



Similar Threads
Thread Thread Starter Forum Replies Last Post
Buffered Reader is not reading my file properly... HELP! mannyT File I/O & Other I/O Streams 8 09-11-2009 12:14 AM
Strings Leeds_Champion Algorithms & Recursion 3 04-11-2009 02:09 AM
greetings and a file reader problem chileshe File I/O & Other I/O Streams 0 06-10-2009 08:45 AM
Returning Random Strings from an Array cfmonster Collections and Generics 3 09-09-2009 04:13 AM
File Reader... help please Truffy File I/O & Other I/O Streams 4 19-05-2009 11:11 PM


100 most searched terms
Search Cloud
2 dimensional arraylist java 2d arraylist java actionlistener actionlistener in java addactionlistener addactionlistener java convert double to integer java double format java double to integer in java double to integer java drag en drop programmeren java eclipse shortcut keys exception in thread "awt-eventqueue-0" java.lang.outofmemoryerror: java heap space exception in thread "main" java.lang.nullpointerexception exception in thread "main" java.lang.outofmemoryerror: java heap space format double in java format double java get mouse position java java 2d arraylist java actionlistener java double format java double formatting java double to int java double to integer java format double java forum java forums java get mouse position java list to map java mouse position java programming forum java programming forums java programming practice problems java send keystrokes to another application java two dimensional arraylist java.io.ioexception: premature eof java.lang.classformaterror: truncated class file java.lang.outofmemoryerror: java heap space java.util.arraylist jbutton action jbutton actionlistener jtextarea font jtextfield font size jxl.read.biff.biffexception: unable to recognize ole stream programming mutators and generics smack api two dimensional arraylist two dimensional arraylist java unable to sendviapost to url what is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

All times are GMT. The time now is 02:05 AM.
Powered by vBulletin® Copyright ©2000-2009, Jelsoft Enterprises Ltd.