Page 1 of 2 12 LastLast
Results 1 to 20 of 26
  1. #1
    Kevinius is offline Member
    Join Date
    Mar 2011
    Posts
    46
    Rep Power
    0

    Default Reading data from a text file

    I have a file that contains a group of people's first name, last name, and their hourly wage (Ex: John Doe, 25.00). I've created variables to hold the information. How does one populate the variables with the info from the file?

    I was considering using file.next() to move one token at a time.

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    You need to set up some sort of reader to read the information from the file. You will probably need a few arrays as well(or 2D arrays, or a class)

    I suggest you read a bit about reading from a file on the oracle tutorials.

    Lesson: Basic I/O (The Java™ Tutorials > Essential Classes)

  3. #3
    Kevinius is offline Member
    Join Date
    Mar 2011
    Posts
    46
    Rep Power
    0

    Default

    I have a class called Person which stores values for first name, last name, and wage. This class also has methods to manipulate the hourly wage. I've managed to output the content of the file in the jTextArea.

    This is the code:
    Java Code:
     try {
                Scanner inFile = new Scanner(new FileReader("Information.txt"));
                int count = 0;
                while (inFile.hasNextLine()) {
                    this.jTextArea1.append(NEWLINE + inFile.nextLine());
                    count++;
                }
            } catch (FileNotFoundException ex) {
                Logger.getLogger(Income.class.getName()).log(Level.SEVERE, "FILE NOT FOUND", ex);
            }
    I guess my problem is going back into the file again. Do I need to create a new FileReader?

  4. #4
    Kevinius is offline Member
    Join Date
    Mar 2011
    Posts
    46
    Rep Power
    0

    Default

    The assignment I'm working on asks that I print the contents of the file (taken care of), and then calculate weekly, biweekly, monthly, and yearly salary (I have these calculations done in Person class). I'm trying to grab individual tokens and assign them to variables. I keep getting a nullPointerException when I try to output the section highlighted in red.

    Java Code:
    try {
                Scanner inFile = new Scanner(new FileReader("Information.txt"));
                int count = 0;
                while (inFile.hasNextLine()) {
                    this.jTextArea1.append(NEWLINE + inFile.nextLine());
                    count++;
                }
    // 
                Person[] person = new Person[count];
    
                for (int i = 0; i < count; i++) {
                    while (inFile.hasNext()) {
                        String fname = inFile.next();
                        String lname = inFile.next();
                        double wage = inFile.nextDouble();
                        person[i] = new Person(fname, lname, wage);
                    }
                }
    
                this.jTextArea1.append(NEWLINE);
                [COLOR="Red"]this.jTextArea1.append(person[2].getFname() + " " + person[2].getLname() + " " + person[2].getWage());[/COLOR]        
            } catch (FileNotFoundException ex) {
                Logger.getLogger(Income.class.getName()).log(Level.SEVERE, "FILE NOT FOUND", ex);
            }

  5. #5
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    It would probably be easier to create an array of people,and from that array display the people. Is there any sort of delimiters in the text file? or is it just space delimited? Is it one person per line? If it is, you can read a line, split it by the delimiter(space or other) and create a person object out of each line. Then store each person in the people array. This will allow you to setup the format you want to print in in the classes toString method. Here is some quick pseudocode

    Java Code:
    declare person array
    declare string
    while loop extracts string in condition
      split string into an array
      use array contents to create a person
      add person to person array
    end while loop
    finally
      close streams
    end finally
    
    loop person array
      print each person
    end loop
    
    loop person array
      calculations
    end loop

  6. #6
    Kevinius is offline Member
    Join Date
    Mar 2011
    Posts
    46
    Rep Power
    0

    Default

    The only delimiters in the file are "," which separates the name (firstname lastname) from the hourly wage.

    Ex:
    John Doe, 21.50
    Suzy Q, 25.80
    Johnny Rocket, 10.15

    I just might use the delimiter to capture the full name (instead of first and last as I did) and the hourly wage. I'll see what I can come up with.

  7. #7
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    You can use whitespace as the delimiter but remember to cut the comma off the end of the lastname.

  8. #8
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Alright, you could always do something like
    Java Code:
    String[] person = line.split(",");
    String[] name = person[0].split(" ");
    With this person[1] will be the wage, and name[0] and name[1] will be the persons name. Try playing around with reading and splitting up the information and see where that gets you. My pseudo-code should give you a lot to go on as well. If you need more help, try looking at the oracle io tutorials, and googling for reading text files in java.

  9. #9
    Kevinius is offline Member
    Join Date
    Mar 2011
    Posts
    46
    Rep Power
    0

    Default

    I've been trying my best to implement the pseudocode, but I'm running into problems. Reading it sounds perfect...trying to make it happen isn't quite as simple. I appreciate the help though...I'm just going to skip the assignment.

  10. #10
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Don't skip the assignment, it's definitely good to learn this. What code have you come up with, what parts are you having trouble?

    If you are interested in learning Java you should absolutely take the time to solve this.

  11. #11
    Kevinius is offline Member
    Join Date
    Mar 2011
    Posts
    46
    Rep Power
    0

    Default

    I've been at this particular portion for 9 hours. The only thing I can do is read and display the content of the file. Trying to assign a line(inFile.nextLine()) to a variable isn't working out to well. I understood the .split method, but having to create two arrays just to store the information is a bit much. Having to pull that information from those arrays and into an instantiated Person object just seems like a lot to ask.

    I haven't come up with anything that works...let's put it that way! Haha.

  12. #12
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    Yeah it is a bit much. So get rid of the unecessary step.

    Read line
    spilt line
    create Person object
    add Person object to array.

    Note how you do not need to store name and wage into arrays. If you put those four steps inside a loop you are done.

  13. #13
    Kevinius is offline Member
    Join Date
    Mar 2011
    Posts
    46
    Rep Power
    0

    Default

    using the .split() method actually uses arrays to store the info.

  14. #14
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    What does your loop look like currently? If you have the person class created you are pretty close. You can store the lines from the file in an array, after splitting by spaces. This way, however; requires you to delete the , from the last name.

    Java Code:
    String[] lines = line.split(" ");
    //delete comma
    That's why I created 2 local arrays and assigned them to the split up lines.

  15. #15
    Kevinius is offline Member
    Join Date
    Mar 2011
    Posts
    46
    Rep Power
    0

    Default

    The Person class was created probably about 6 hours ago and took a matter of minutes. My problem is getting the values that were split into my Person class. It says that I can instantiate.

    Java Code:
    Scanner inFile = new Scanner(new FileReader("Information.txt"));
                while(inFile.hasNextLine()){
                    line = inFile.nextLine();
                    String[] lines = line.split(" ");
                   [COLOR="Red"] lines = new Person(first, last, wage);[/COLOR]                count++;
                }

  16. #16
    Kevinius is offline Member
    Join Date
    Mar 2011
    Posts
    46
    Rep Power
    0

    Default

    I just realized that the number in the file is actually a String type. I've got to parse it to Double.

  17. #17
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    While
    Java Code:
    Scanner inFile = new Scanner(new FileReader("Information.txt"));
                while(inFile.hasNextLine()){
                    line = inFile.nextLine();
                    String[] lines = line.split(" ");
                    lines = new Person(first, last, wage);                count++;
                }
    is close, you are off by a bit still. the variable lines is a string[] declared inside the loop, which is not what you want to be assigning a person object to.

    Java Code:
    Scanner inFile = new Scanner(new FileReader("Information.txt"));
                while(inFile.hasNextLine()){
                    line = inFile.nextLine();
                    String[] lines = line.split(" ");
                    Person p = new Person(lines[0], lines[1], parse string on lines[3]);
                    add p to the array of people declared outside of the loop
                 }
    I helped you a bit here, be glad I gave up so much, try to understand how what I did is different than what you had.

  18. #18
    Kevinius is offline Member
    Join Date
    Mar 2011
    Posts
    46
    Rep Power
    0

    Default

    I came up with something similar. I'd be done, but I'm running into a problem "printing" to the JTextArea. It wants a string, but the value I'm trying to print is a double.

    Java Code:
    int count = 0;
            String line = null;
            String[] lines = new String[count];
            Person[] person = new Person[count];
            try {
                Scanner inFile = new Scanner(new FileReader("Information.txt"));
    
                while(inFile.hasNextLine()){
                    line = inFile.nextLine();
                    lines = line.split(" ");
                    count++;
                }
                inFile.close();
    
                for (int i = 0; i < count; i++){
                    double wage = Double.parseDouble(lines[2]);
                    String fname = lines[0];
                    String lname = lines[1];
                    person[i] = new Person(fname, lname, wage);
                }
                [COLOR="Red"]this.jTextArea1.append(person[0].getBiWeeklyIncome());[/COLOR]
            } catch (FileNotFoundException ex) {
                Logger.getLogger(Income.class.getName()).log(Level.SEVERE, "File not found!", ex);
            }

  19. #19
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    Quote Originally Posted by Kevinius View Post
    using the .split() method actually uses arrays to store the info.
    Correct. I misunderstood and thought you were talking about an array of names and an array of wages.

  20. #20
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    What error are you getting? Can you copy/paste the error please?

    I don't believe lines and person have sizes of more than 1. When you initialize the array the size is set, it doesn't get changed as the variable count changes. If you have an unknown amount of lines to read it may be better to use an arrayList.

Page 1 of 2 12 LastLast

Similar Threads

  1. Reading Text file to Data type Double
    By orpheus2708 in forum New To Java
    Replies: 17
    Last Post: 04-08-2011, 04:11 AM
  2. Replies: 2
    Last Post: 03-25-2011, 03:36 PM
  3. Problem Reading in data from Text Field
    By markious in forum AWT / Swing
    Replies: 2
    Last Post: 02-12-2010, 03:29 AM
  4. Reading data from a text file
    By Cheguvara in forum New To Java
    Replies: 2
    Last Post: 02-02-2010, 03:33 PM
  5. reading data from text file .. help plz
    By Thug heart in forum New To Java
    Replies: 7
    Last Post: 02-15-2009, 08:29 PM

Posting Permissions

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