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.

Results 1 to 17 of 17

Thread: Reading into a File and storing it into an Array

  1. #1
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Reading into a File and storing it into an Array

    Hello JavaWorld,

    I'm having trouble with this program. I don't understand why I am getting an exception thrown to me. I am successfully reading the file, and displaying it's contents on my console. Then I attempt to store the contents into a String file, and then I plan on storing the contents into an ArrayList.
    ArrayList<String>Question=new ArrayList();
    public void ReadFile() throws IOException{
     Scanner sr = new Scanner(System.in);
     System.out.println("Please enter file name");
     String fileName = sr.nextLine();
     File infile = new File("C:\\test\\"+fileName+".txt");
     if(infile.exists()){
      System.out.println("The quiz file has been found");
      }
     else{
     System.out.println("Sorry, the file has not been found");
    }
    Scanner  file = new Scanner(new File("C:\\test\\"+fileName+".txt"));
     while(file.hasNext()){
         System.out.println(file.next());
         String str = file.next();
     
     
     
     }

    I honestly don't see where I am going wrong here. It's pretty straightforward. I limited the text file to just"hi" and still it wont work. Any input would be greatly appreciated.
    Thanks in advance.


  2. #2
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Reading into a File and storing it into an Array

    I solved the problem I just made a new scanner and it worked perfectly. So if I understand this correctly, I need two different Scanner objects one for reading the file and seeing if it existed, and the second Scanner object I can make by typing in
        sr = new Scanner(new File("C:\\test\\" + fileName + ".txt"));
    . So this way the same object "sr" is now referencing a new object. Does this explain it. By point or referencing the new scanner object it worked perfectly. Now I am able to add the input into the arraylist.

  3. #3
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Reading into a File and storing it into an Array

    Quote Originally Posted by loui345 View Post
    I solved the problem I just made a new scanner and it worked perfectly...
    In the first place, you didn't say what about the original code didn't "work." Did it run for a while and then throw an exception? Or what? When you say something didn't "work" it leaves it up to us to guess. That's not the way I like to work.

    In the second place, there is no need for a new and separate Scanner for the file.

    How about showing complete code that "doesn't work" and that "works," so that we can all come to an understanding?


    Now, about "working perfectly", assuming that you added your fix and didn't change anything else, did you notice that your code was only printing every other word from the file? Depending on whether the file had an odd number of words or even number of words, it could have thrown an IOException:

    Here's your loop with a couple of comments that I added:
            while(file.hasNext()) { // Enter the loop as long as there is a next String
                System.out.println(file.next()); // Read a String and print it
                String str = file.next();        // Read another String.  Will eventually put it into the ArrayList
    .
    .
    .


    Bottom line: More information, please. I'm really interested, and there are lots of people who follow threads like this, looking for things like this, hoping to learn. Maybe your "fix" actually fixed something, but I would have to see a little more to grasp its true implications.


    Cheers!

    Z

  4. #4
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Reading into a File and storing it into an Array

    When I was trying to store the file into the String
      String str = file.next();
    that was throwing me an exception error. So I just used trial and error and
      sr = new Scanner(new File("C:\\test\\" + fileName + ".txt"));
    and it worked. I then tried to theorize on why it worked and wrote an explanation on why i believed it to work. Now I am having additional trouble.


    I am trying to store the text file in it's entirety into an arraylist. I know how to do it with a regular array. I would create a loop and increment it in. This method doesn't work with an arraylist. So I attempted to do this
     while(sr.hasNext()){
           int i = 0;
     
        String a = sr.next();
     
     
        Question.add(a);
        System.out.println(Question.get(1));

    In my mind, this makes perfect sense. The variable is stored in "a", and I add it into the Arraylist as the loop continues. I ran a quick test and I get an outbound exception thrown, which tells me it's not working probably. I am stuck once again. It should work.

  5. #5
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 139 Times in 134 Posts

    Default Re: Reading into a File and storing it into an Array

    Quote Originally Posted by loui345 View Post
    I am trying to store the text file in it's entirety into an arraylist. I know how to do it with a regular array. I would create a loop and increment it in. This method doesn't work with an arraylist. So I attempted to do this
     while(sr.hasNext()){
           int i = 0;
     
        String a = sr.next();
     
     
        Question.add(a);
        System.out.println(Question.get(1));

    In my mind, this makes perfect sense. The variable is stored in "a", and I add it into the Arraylist as the loop continues. I ran a quick test and I get an outbound exception thrown, which tells me it's not working probably. I am stuck once again. It should work.
    Your int variable i confuses me as you create it, initialize it, but never use it. You also create it inside of the loop, so it can't be used as an index variable if that was your purpose. You also then get the 2nd item in the Question ArrayList (rename that question by the way to conform with Java naming standards), and get that item before you've added an item to this position.

    Maybe you meant
    int i = 0;
    while (sr.hasNext() {
      Question.add(sr.next());
      System.out.println(Question.get(i));
      i++;
    }
    ?
    Last edited by curmudgeon; October 19th, 2012 at 09:58 PM.

  6. #6
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Reading into a File and storing it into an Array

    No, that won't work. Any other ideas curmudgeon. Shouldn't it work? Is there an error on my understanding. It seems pretty straight forward.

  7. #7
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 139 Times in 134 Posts

    Default Re: Reading into a File and storing it into an Array

    Quote Originally Posted by loui345 View Post
    No, that won't work. Any other ideas curmudgeon. Shouldn't it work? Is there an error on my understanding. It seems pretty straight forward.
    Your code would never work. You're getting the second item in the list by calling get(1) (remember lists are 0-based -- they start at 0), before a 2nd item has been added.

    Why won't my suggestion work? Have you re-read the edit to my post?

  8. The Following User Says Thank You to curmudgeon For This Useful Post:

    loui345 (October 19th, 2012)

  9. #8
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Reading into a File and storing it into an Array

    Yes, you're 100 percent correct. I could kiss you. I forgot to i++, and you also pointed out when I was calling the ArrayList I needed to call it after the while loop. Because I forgot the increment the i++, I thought that my logic was flawed, so I attempted to test it by calling the ArrayList's index at [1], and I was getting an out of bound exception. Now I understand, so again thanks curmudgeon.

  10. #9
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 139 Times in 134 Posts

    Default Re: Reading into a File and storing it into an Array

    You're quite welcome, but please, keep your kisses to yourself.

    Also, do you see the problem with declaring and initializing the i variable *inside* of the while loop?

  11. #10
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Reading into a File and storing it into an Array

    No, I don't see the problem?

  12. #11
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Reading into a File and storing it into an Array

    I am not sure if you've more mental energy to solve another problem I have. See the whole problem I have is I am not actually a member of the school. I found the school and they leave the homework assignments accessible to the public. I try and complete the assignments the best way I can. I don't have the option of actually asking the instructor or TA for assistance on the assignment.

    My problem is
        for(int i = 0; i < Question.size(); i++)  
        {  
          System.out.print(Question.get(i)+" ");  
          if((Question.get(i)).equalsIgnoreCase("?")){
        System.out.println("\n");

    I believe the assignment wants me to store the question in the ArrayList and then print it out in a quiz like format. For example, the output should be like this:How many licks does it take to get to the tootsie roll center of a tootsie pop ?
    1.2
    2.3
    3.4
    4.4

    So I am confused on how to get the code to print out like that correctly. Any suggestions, would greatly be appreciated.

  13. #12
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Reading into a File and storing it into an Array

    Anyone have some suggestions?

  14. #13
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Reading into a File and storing it into an Array

    I believe the assignment wants me to ...
    If you post your given instructions it will be easier to help you figure out what is needed.



    store the question in the ArrayList and then print it out in a quiz like format
    I am not sure what that means. Try to create a step by step process to solve the problem, and when you get stuck post the process and any question you have.

  15. #14
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Reading into a File and storing it into an Array

    Okay, sorry about my vague post earlier it was 3:00am at the time and my mind wasn't functioning correctly. Anyhow, " You must store your Questions in an ArrayList and access the questions via the ArrayList.

    • The file access for this program is again fairly straightforward. The file is formatted in such a way as to make the input and extraction of the data fairly simple. However, note that some of the data read in is String data and some is int data – be careful to handle these types appropriately." This is what is expected of me. I am able to print this data out from my ArrayList,which looks like this:"How many licks does it take to get to the tootsie roll center of a tootsie pop ?
    1.2 2.3 3.4 4.4" The data should look like this:
    How many licks does it take to get to the tootsie roll center of a tootsie pop ?
    1. 5
    2. 6
    3. 7
    4. 8

    I believe the instructions want me to first store the data from a text file into an Array, and then from the ArrayList print the data in a quiz like format. The trouble I am having is getting the data to print newlines for the user to select the answer. So any help in pointing me in the right direction would be greatly appreciated.

    for(int i = 0; i < Question.size(); i++)  
        {  
          System.out.print(Question.get(i)+" ");  
          if((Question.get(i)).equalsIgnoreCase("?")){
        System.out.print("\n");
    }
        }

    This is my attempt at trying to get a new line. I look for the question mark in the output from the Array, and then create a newline by using the newline character. It doesn't work, so any other suggestions would be greatly appreciated.

    Thanks

  16. #15
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Reading into a File and storing it into an Array

    Hi I made a lot of progress since I last posted this. Sometimes I realize that taking a few minute break and coming back I can see solutions that wasn't apparent initially. Unfortunately, for me a solution usually leads to another problem. I was able to print the data correctly, and when I say correctly I mean in this format:
    "How many licks does it take to get to the tootsie roll center of a tootsie pop?
    4
    one
    two
    three
    four "
    Now I have done that it almost is perfect but for some reason I am getting erroneous information. My output is:
    How many licks does it take to get to the tootsie roll center of a tootsie pop? " 4 0:4"
    1ne
    2:two
    3:three
    4:four

    I am unsure on why I am getting that bit of extra info on my output.
     // I create a loop display the ArrayList on oneline with a space
        for(int i = 0; i < Question.size(); i++)  
        {  
    // I am postive that this line of code is creating the extra data
          System.out.print(Question.get(i)+" ");
         // I create an If statement and search for the integer 4
          if((Question.get(i)).equalsIgnoreCase("4")){
                for(int is =17 ; is < Question.size(); is++) {
                 // I then loop again from the interger 4 displaying the data on new seperate lines 
             // I then use "is" to increment and subract 17 this allows me to add to count each answer 1 through 4 on new lines
              System.out.println(is-17+":"+Question.get(is));
                }
               // I then created an enhanced loop to once again cycle through the ArrayList and remove  the last part of the Array. If I do not do this it will continue to loop and give me data
               // that I don't need. 
               for(String X: Question){
               Question.remove(20);
                 Question.remove(19);
                 Question.remove(18);
                 Question.remove(17);
             break;
               }
     
                }
     
    }
    When I try to mentally map it out it makes sense in my head, but the compile sees it a different way. I tried to make my problem as unambiguous as possible. If I am not clear enough, please let me know. Also, I am not in the class I am just doing the homework assignments, so I can become a better programmer in life.

  17. #16
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Reading into a File and storing it into an Array

    anyone have a suggestion?

  18. #17
    Member
    Join Date
    Jun 2012
    Posts
    105
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Reading into a File and storing it into an Array

    can anyone tell me if I am in the right direction?

Similar Threads

  1. Reading a txt file and storing them in a Java Array
    By FrozenFox in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: July 27th, 2012, 07:19 AM
  2. Storing data from a file in array and setting it to textbox
    By macko in forum What's Wrong With My Code?
    Replies: 4
    Last Post: May 13th, 2011, 09:17 PM
  3. HELP with reading a clients ip address and storing in a text file.
    By dannyyy in forum Java Theory & Questions
    Replies: 1
    Last Post: April 4th, 2011, 07:20 AM
  4. [SOLVED] Reading from a text file and storing in arrayList
    By nynamyna in forum What's Wrong With My Code?
    Replies: 2
    Last Post: April 26th, 2010, 09:55 PM
  5. Reading .txt and storing into an array
    By vluong in forum Collections and Generics
    Replies: 1
    Last Post: January 4th, 2010, 01:07 PM