Results 1 to 16 of 16
  1. #1
    darby8812345 is offline Member
    Join Date
    May 2014
    Posts
    8
    Rep Power
    0

    Default populate an array from txt file or scanner

    hello everyone,

    I have a simple txt file, each line simply containing 1 word.

    I would like each work to represent an index of the array

    im having some difficulty populating an array from either a txt file or a scanner.

    i seem to be able to fill the scanner so to speak with the contents of the text file but not the array. I don't know how to syntax it

    ill attach my file an also paste my code below.

    I would appreciate some help.

    thanks


    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    import java.util.Arrays;

    public class ReadFile {
    public static void main(String[] args) {

    // Location of file to read
    File file = new File("dictionary.txt");

    try {
    Scanner sc = new Scanner(file);

    int count = 0;
    while (sc.hasNextLine()) {
    count++;
    sc.nextLine();
    }
    System.out.println(count);



    while (sc.hasNextLine()) {
    String line = sc.nextLine();
    System.out.println(line);


    }
    sc.close();
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    }
    }
    }
    Attached Files Attached Files

  2. #2
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,616
    Rep Power
    5

    Default Re: populate an array from txt file or scanner

    Check out the Java tutorials in my signature for information on arrays and how to use them.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  3. #3
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    1

    Default Re: populate an array from txt file or scanner

    Just go through the code yourself:
    First you go through the file and count the lines. At the end the loop quits and the next loops comes. But you are already at the end of the list so the loop is not executed.

    Just merge the 2 loops to one loop.
    So just incr. the count variable, store the line inside the variable line and then print it.

    Did that help or do you need more explanations?

    With kind regards,

    Konrad

  4. #4
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,616
    Rep Power
    5

    Default Re: populate an array from txt file or scanner

    I suspect the OP is reading the file once to get a size so the array can be properly allocated. I have seen this before and I would normally recommend using a List to avoid this. But sometimes the professors don't want that. In any case, you are correct. The OP needs to at least close and reopen the file.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  5. #5
    darby8812345 is offline Member
    Join Date
    May 2014
    Posts
    8
    Rep Power
    0

    Default Re: populate an array from txt file or scanner

    Quote Originally Posted by kneitzel View Post
    Just go through the code yourself:
    First you go through the file and count the lines. At the end the loop quits and the next loops comes. But you are already at the end of the list so the loop is not executed.

    Just merge the 2 loops to one loop.
    So just incr. the count variable, store the line inside the variable line and then print it.

    Did that help or do you need more explanations?

    With kind regards,

    Konrad
    thanks Konrad and Jim for your replies.

    to be honest I just use print going through my code it ensure that I'm getting the desired results.

    I'm just really at a wall on this. Sorry I might not have explained very well. but id just like to get the strings contained in the txt file into an array which i can later reference. i don't actually need to print what is in the text file.

    so I'm counting the lines so I can as Jim says make the array dynamic if needs be.
    now that I have the size of the array I need I need to populate it, unfortunately I cant seem to do it though

    thanks again

  6. #6
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,616
    Rep Power
    5

    Default Re: populate an array from txt file or scanner

    Do you know how to create arrays? Check out this link for help. Arrays (The Java™ Tutorials > Learning the Java Language > Language Basics).

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  7. #7
    darby8812345 is offline Member
    Join Date
    May 2014
    Posts
    8
    Rep Power
    0

    Default Re: populate an array from txt file or scanner

    Quote Originally Posted by jim829 View Post
    Do you know how to create arrays? Check out this link for help. Arrays (The Java™ Tutorials > Learning the Java Language > Language Basics).

    Regards,
    Jim
    thanks Jim,

    I know how to make simple arrays where the size of the array is small and each index can be declared as per your example

    anArray = new int[10];


    anArray[2] = 300;
    anArray[3] = 400

    I think my problem is assigning each index of the array to each variable line in the text file.
    so id need something like below to loop through each line in the file adding the strings one by one as i have about 50,000 stings in the file, each on a separate lines

    int x = 0;
    while( x < txt file line count ) {
    anArray[x] = //code to add the string from the text file***
    x++;
    }

    i just don't know what that code would be to add it.

    thanks

  8. #8
    darby8812345 is offline Member
    Join Date
    May 2014
    Posts
    8
    Rep Power
    0

    Default Re: populate an array from txt file or scanner

    I think I'm getting closer (hopefully) but still seeing one error, what do you guys think?

    Java Code:
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    import java.util.Arrays;
    
    public class Main {
        public static void main(String[] args) {
            String fileName ="dictionary.txt";
            File file = new File(fileName);
            try {
                Scanner input = new Scanner(file);
                while(input.hasNext()) {
                    String data = input.next();
                    String [ ] values = data;
                    
                    System.out.println(values [ ]);
                }
                input.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
    cheers
    Last edited by darby8812345; 05-27-2014 at 02:03 AM.

  9. #9
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,421
    Rep Power
    25

    Default Re: populate an array from txt file or scanner

    still seeing one error,
    Copy the full text of the error message and paste it here.

    Please edit your post and wrap your code with code tags:
    [code]
    YOUR CODE HERE
    [/code]
    to get highlighting and preserve formatting.

    See the tutorial: http://docs.oracle.com/javase/tutori...ts/arrays.html
    If you don't understand my response, don't ignore it, ask a question.

  10. #10
    darby8812345 is offline Member
    Join Date
    May 2014
    Posts
    8
    Rep Power
    0

    Default Re: populate an array from txt file or scanner

    my error is pointing at line 16

    Java Code:
    System.out.println(values [ ]);
    error: '.class' expected

  11. #11
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,421
    Rep Power
    25

    Default Re: populate an array from txt file or scanner

    What is that statement trying to print?
    If it's an element of the array, it needs an index value inside of the []s.
    If it's the contents of the whole array, it needs to use the Arrays class's toString() method to format it:
    System.out.println("an ID "+ java.util.Arrays.toString(theArrayNameHere));
    If you don't understand my response, don't ignore it, ask a question.

  12. #12
    darby8812345 is offline Member
    Join Date
    May 2014
    Posts
    8
    Rep Power
    0

    Default Re: populate an array from txt file or scanner

    Quote Originally Posted by Norm View Post
    What is that statement trying to print?
    If it's an element of the array, it needs an index value inside of the []s.
    If it's the contents of the whole array, it needs to use the Arrays class's toString() method to format it:
    System.out.println("an ID "+ java.util.Arrays.toString(theArrayNameHere));
    thank you Norm


    yes im trying to print the entire array

    Java Code:
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    import java.util.Arrays;
    
    public class Main {
        public static void main(String[] args) {
            String fileName ="dictionary.txt";
            File file = new File(fileName);
            try {
                Scanner input = new Scanner(file);
                while(input.hasNext()) {
                    String data = input.next();
                    String [ ] values = data;
    
                    System.out.println("an ID "+ java.util.Arrays.toString(values));
                }
                input.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
    trying your suggested method seems to give me an error on line 14

    Java Code:
    String [ ] values = data;
    ''incompatible types: String cannot be converted to String[]''

  13. #13
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,421
    Rep Power
    25

    Default Re: populate an array from txt file or scanner

    Look at how it was coded in post#7. That was mostly correct.

    String cannot be converted to String[]'
    The start of that statement (to the left of the =) looks like a definition for a String array named values.
    The value to the right of the = is NOT a String array, its a String: data.
    The compiler is complaining that a String can't be converted to a String array to assign to values.

    What is the purpose of that statement on line 14?
    If you don't understand my response, don't ignore it, ask a question.

  14. #14
    darby8812345 is offline Member
    Join Date
    May 2014
    Posts
    8
    Rep Power
    0

    Default Re: populate an array from txt file or scanner

    Quote Originally Posted by Norm View Post
    Look at how it was coded in post#7. That was mostly correct.


    The start of that statement (to the left of the =) looks like a definition for a String array named values.
    The value to the right of the = is NOT a String array, its a String: data.
    The compiler is complaining that a String can't be converted to a String array to assign to values.

    What is the purpose of that statement on line 14?
    this is confusing now, your saying that I can't populate a string array with string variables?

    Do you have an example or pointing out how I could restructure my code?

    Thanks

  15. #15
    darby8812345 is offline Member
    Join Date
    May 2014
    Posts
    8
    Rep Power
    0

    Default Re: populate an array from txt file or scanner

    What do you think of changing line 20 to
    Java Code:
    String[x] values = data; 
    X++
    That way I wouldn't be trying to assign a string array to string but rather an index of the array?

  16. #16
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,421
    Rep Power
    25

    Default Re: populate an array from txt file or scanner

    Look at the code in post#7.
    Look at the tutorial linked to in post#9

    String[] name; // defines a String array
    name = new String[3]; // gives the array a value
    name[0] = "AD"; // assigns a value to one of the elements in the array
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. Replies: 18
    Last Post: 04-21-2014, 02:00 PM
  2. Replies: 1
    Last Post: 11-05-2012, 01:08 AM
  3. using an if statement to populate an array
    By MrJinx in forum New To Java
    Replies: 3
    Last Post: 04-30-2011, 12:01 PM
  4. Populate an array dynamically
    By mmarkym in forum New To Java
    Replies: 11
    Last Post: 12-31-2010, 03:31 PM
  5. Ripping apart a array list to populate a vector
    By Adrien in forum AWT / Swing
    Replies: 0
    Last Post: 03-07-2010, 09:55 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
  •