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 24 of 24

Thread: Using for loop to read in data from text file using Scanner class

  1. #1
    Junior Member
    Join Date
    Feb 2013
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Using for loop to read in data from text file using Scanner class

    Hi guys,

    I'm currently stuck on a programming assignment which requires me to read in data from a text file then process it. The file looks like this:

    CS1 2012 Group 1
    8
    5,5,5,6,5,8,9,5,6,8, good, very good, excellent, good
    7,7,8,7,6,7,8,8,9,7,very good, Good, excellent, very good
    8,7,6,7,8,7,5,6,8,7 ,GOOD, VERY GOOD, GOOD, AVERAGE
    9,9,9,8,9,7,9,8,9,9 ,Excellent, very good, very good, excellent
    7,8,8,7,8,7,8,9,6,8 ,very good, good, excellent, excellent
    6,5,6,4,5,6,5,6,6,6 ,good, average, good, good
    7,8,7,7,6,8,7,8,6,6 ,good, very good, good, very good
    5,7,6,7,6,7,6,7,7,7 ,excellent, very good, very good, very good

    The first 2 lines are read in then assigned to fields, the remaining lines are the ones I have to process. I've been told to use .useDelimiter("[ ]*(,)[ ]*") but so far haven't really been able to put it to good use.

    Once the data has been read in I have to convert the Strings into integers using a switch statement and work out an average feedback score e.g excellent = 5 very good = 4 good =3. Maybe i'm just not thinking clear but I've already spent about 5 hours trying to figure this out to no avail so any guidance would be appreciated. Thanks!


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    write the code in simple steps.
    First make a loop and in the loop read a line and print it
    continue until all the lines have been read and printed.
    When that works, then worry about how to parse the contents of a line and use the data it contains.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Feb 2013
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    Thanks for your responses. This is my attempt:

        public void readMarksData(String fileName, int numberOfStudents, int responsesPerStudent) throws FileNotFoundException
        {
            int feedbackScore;
            studentResponses = new int[numberOfStudents][responsesPerStudent]; //Creates 2D array
            File dataFile = new File(fileName);
            Scanner scanner = new Scanner (dataFile);
     
            cohort = scanner.nextLine(); //Assigns the first line of the text file to the field "cohort"
            System.out.println (cohort);
            int numberOfResponses = scanner.nextInt(); //Assigns the second line of the text file to the field "numberOfResponses"
            System.out.println (numberOfResponses);
     
            scanner.useDelimiter("[ ]*(,)[ ]*");      
     
            for (int row = 0; row < studentResponses.length; row++)
            {
                for (int column = 0; column < studentResponses[0].length; column++){
                    studentResponses[row][column] = scanner.nextInt();
                    System.out.print(studentResponses[row][column]); 
                }          
     
            }
            scanner.close();
     
        }
    Once it gets to the studentResponses[row][column] = scanner.nextInt(); part I get this error: "java.util.InputMismatch exception: null(in java.util.Scanner)".

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    Please edit your post and wrap your code with
    [code=java]
    <YOUR CODE HERE>
    [/code]
    to get highlighting and preserve formatting.

    Where is the loop that reads the lines and prints them out?

    Does that part of the code work?

    When that part works, then move to the parsing of the line to get the data on the line.
    How will the code get the data from the line? Make a list of the steps it should use to get the various pieces of data contained on the line.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Feb 2013
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    The loop that prints out everything being read in is

                for (int column = 0; column < studentResponses[0].length; column++){
                    studentResponses[row][column] = scanner.nextInt();
                    System.out.print(studentResponses[row][column]); 
                }

    Everything else above the loop works

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    The loop that prints out everything being read in is
    That loop doesn't read a line, it reads tokens.

    If you read a line first and then parse that line, you will have better control over what happens.
    You described the lines in the file as having different parts: ints and Strings.
    It will be easier to work on a line by line basis than with token by token
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Feb 2013
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    I see, so what modifications would you suggest I make to my code?

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    Start by making a loop that reads the lines and prints them.

    When that works, work on how to parse the data in the line.
    Describe what data is on a line and say where that data should be saved.
    When you can describe where each part of the data goes, then work on writing the code to do it.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Feb 2013
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    I think this should work, basically it's going to print out everything again separated by a space rather than comma and put a tab space between the numbers and the strings. However I'm still getting the same error as before and can't figure out why I'm getting it
        public void readMarksData(String fileName, int numberOfStudents, int responsesPerStudent) throws FileNotFoundException
        {
            int feedbackScore;
            studentResponses = new int[numberOfStudents][responsesPerStudent];
            File dataFile = new File(fileName);
     
            Scanner scanner = new Scanner (dataFile);
     
            cohort = scanner.nextLine();
            System.out.println (cohort);
            int numberOfResponses = scanner.nextInt();
            System.out.println (numberOfResponses);
            scanner.useDelimiter(",");      
     
            for (int row = 0; row < 8; row++)
            {
                Scanner scanner2 = new Scanner(scanner.nextLine());
                for (int column = 0; column < studentResponses[0].length-4; column++)
                {
                    scanner2.useDelimiter(",");
                    studentResponses[row][column] = scanner2.nextInt();
                    System.out.print(" "+studentResponses[row][column]); 
                }
                System.out.print("\t");
                for (int column = studentResponses[0].length-4; column < studentResponses[0].length; column++)
                {
                    scanner2.useDelimiter("[ ]*(,)[ ]*");
                    String test = scanner.next();
                    System.out.print(" "+test);
     
                }
                scanner2.close();
            }
            scanner.close();   
         }

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    Have you done this yet?
    Describe what data is on a line and say where that data should be saved.
    When you can describe where each part of the data goes, then work on writing the code to do it.

    Have you given up on my suggestions on how to do this project?

    There are some poor techniques in the posted code:
    for (int row = 0; row < 8; row++)
    Use the number from the file, not an 8 here. What if the data file were changed?

    for (int column = studentResponses[0].length-4; column < studentResponses[0].length; column++)

    What is the -4 for?
    If you don't understand my answer, don't ignore it, ask a question.

  11. The Following User Says Thank You to Norm For This Useful Post:

    Scippi (February 26th, 2013)

  12. #11
    Junior Member
    Join Date
    Feb 2013
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    Well I've asked someone in my class to give me some pointers so I'm just trying out his method. Yeah I usually use studentResponses.length rather than a number, the 8 was just there for testing purposes, I've changed it back now.

    Basically, scanner will pass a whole line of data to scanner2, the first inner loop will loop from element 1 to 10 which are the integer elements which is why I have studentResponses[0].length-4 because there are 14 elements in total and the last 4 are Strings. The second inner loop will loop from 10 to 14 and read in the Strings.

    I'm currently just getting the program to tokenize the data properly and print it to the terminal, the rest is quite easy

  13. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    Have you fixed the error?
    If you don't understand my answer, don't ignore it, ask a question.

  14. #13
    Junior Member
    Join Date
    Feb 2013
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    No, I get the error everytime it gets to the line studentResponses[row][column] = scanner2.nextInt();

  15. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    Please post the full text of the error message.

    Copy the full contents of the console and paste it including the debug print out and the error message.
    If you don't understand my answer, don't ignore it, ask a question.

  16. #15
    Junior Member
    Join Date
    Feb 2013
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    I mentioned this error earlier, the full content of the console is: java.util.InputMismatch exception: null(in java.util.Scanner)

  17. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    I look at a lot of posts and don't remember. It makes it easier if the message is printed or the post# to look at is posted.

    Is Only that one line is the full text of the console???? Normal error message texts have lots more lines to them.
    That means the error is happening somewhere else, not in this method because the posted method has this println in it:
    System.out.println (cohort);
    And that was not printed, which means that the above method was not executed.
    If you don't understand my answer, don't ignore it, ask a question.

  18. #17
    Junior Member
    Join Date
    Feb 2013
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    Oh so sorry, yeah the Cohort and numberOfResponses get printed out fine. The program prints those two lines, then goes to print the actual data, starting with the integers, and that's when the error appears.

        public void readMarksData(String fileName, int numberOfStudents, int responsesPerStudent) throws FileNotFoundException
        {
            int feedbackScore;
            studentResponses = new int[numberOfStudents][responsesPerStudent];
            File dataFile = new File(fileName);
     
            Scanner scanner = new Scanner (dataFile);
     
            cohort = scanner.nextLine();
            int numberOfResponses = scanner.nextInt();
            System.out.println (cohort);
            System.out.println (numberOfResponses);
            scanner.useDelimiter(",");      
     
            for (int row = 0; row < studentResponses.length; row++)
            {
                Scanner scanner2 = new Scanner(scanner.nextLine());
                for (int column = 0; column < studentResponses[0].length-4; column++)
                {
                    scanner2.useDelimiter(",");
                    studentResponses[row][column] = scanner2.nextInt();
                    //System.out.print(" "+studentResponses[row][column]); 
                    //System.out.print(scanner2.nextInt());
                }
                System.out.print("\t");
                for (int column = studentResponses[0].length-4; column < studentResponses[0].length; column++)
                {
                     scanner2.useDelimiter("[ ]*(,)[ ]*");
                     String feedback = scanner2.next();
                     switch (feedback.toLowerCase())
                     {
                         case ("Excellent"): studentResponses[row][column] = 5;
                         break;
                         case ("Very Good"): studentResponses[row][column] = 4;
                         break;
                         case ("Good"): studentResponses[row][column] = 3;
                         break;
                         case ("Average"): studentResponses[row][column] = 2;
                         break;
                         default: studentResponses[row][column] = 1;
     
                     }
                }
     
                scanner2.close(); 
            }
            scanner.close(); 
        }

  19. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    goes to print the actual data, starting with the integers, and that's when the error appears.
    That is what is needed to see where the error is. The last thing printed tells you what was being read when the error happens.
    If you don't understand my answer, don't ignore it, ask a question.

  20. #19
    Junior Member
    Join Date
    Feb 2013
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    The first line is 5,5,5,6,5,8,9,5,6,8, good, very good, excellent, good and I've set the delimiter to a comma so I would've thought it'd print the first integer before crashing since I can't see anything wrong with studentResponses[row][column]=scanner2.nextInt()

  21. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    What was the last thing printed before the error?
    How many numbers were printed before the error?
    What was being read when the error happened?
    Was it a numeric value or a String?
    If you don't understand my answer, don't ignore it, ask a question.

  22. #21
    Junior Member
    Join Date
    Feb 2013
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    Quote Originally Posted by Norm View Post
    What was the last thing printed before the error?
    How many numbers were printed before the error?
    What was being read when the error happened?
    Was it a numeric value or a String?
    CS1 2012 Group 1 - printed first using scanner.hasNextLine()
    8 - printed second as int on a new line scanner.hasNextInt()
    One number was printed before the error which is the 8
    studentResponses[row][column]=scanner2.nextInt() was being read when the error happened

  23. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    One number was printed
    It's important to know what was being read when the error happened so you can change the code to handle the problem. Not copying and pasting here all that was printed just makes the debugging process take more time.

    What line was it reading the numbers from?
    While still debugging the program You need to print out the lines as they are read so you know where the problem is.
    If you don't understand my answer, don't ignore it, ask a question.

  24. #23
    Junior Member
    Join Date
    Feb 2013
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    Here's a screenshot of everything, the attached file is horribly pixelated so use this link : http://i56.tinypic.com/1xxfnn.png
    Attached Images Attached Images

  25. #24
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using for loop to read in data from text file using Scanner class

    Sorry, images are hard to work with. You can't copy text from an image.
    Copy and paste here the full text of the console from when the program is executed.

    I'm done for tonight. Back tomorrow.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Help with Scanner class - Reading Data from a file
    By billias in forum What's Wrong With My Code?
    Replies: 7
    Last Post: June 28th, 2011, 12:07 PM
  2. Replies: 8
    Last Post: March 25th, 2011, 02:34 PM
  3. Read data from text file
    By yroll in forum Algorithms & Recursion
    Replies: 4
    Last Post: December 31st, 2009, 01:40 AM
  4. Reading a file line by line using the Scanner class
    By JavaPF in forum File Input/Output Tutorials
    Replies: 0
    Last Post: April 17th, 2009, 07:34 AM
  5. Reading a file line by line using the Scanner class
    By JavaPF in forum Java Code Snippets and Tutorials
    Replies: 0
    Last Post: April 17th, 2009, 07:34 AM