1

I am having trouble with a programming assignment. I need to read data from a txt file and store it in parallel arrays. The txt file contents are formatted like this:

Line1: Stringwith466numbers
Line2: String with a few words
Line3(int): 4
Line4: Stringwith4643numbers
Line5: String with another few words
Line6(int): 9

Note: The "Line1: ", "Line2: ", etc is just for display purposes and isn't actually in the txt file.

As you can see it goes in a pattern of threes. Each entry to the txt file is three lines, two strings and one int.

I would like to read the first line into an array, the second into another, and the third into an int array. Then the fourth line would be added to the first array, the 5th line to the second array and the 6th line into the third array.

I have tried to write the code for this but can't get it working:

//Create Parallel Arrays
String[] moduleCodes = new String[3];
String[] moduleNames = new String[3];
int[] numberOfStudents = new int[3];

String fileName = "myfile.txt";


readFileContent(fileName, moduleCodes, moduleNames, numberOfStudents);

private static void readFileContent(String fileName, String[] moduleCodes, String[] moduleNames, int[] numberOfStudents) throws FileNotFoundException {

        // Create File Object 
        File file = new File(fileName);

        if (file.exists())
        {

            Scanner scan = new Scanner(file);
            int counter = 0;

            while(scan.hasNext())
            {


                String code = scan.next();
                String moduleName = scan.next();
                int totalPurchase = scan.nextInt();

                moduleCodes[counter] = code;
                moduleNames[counter] = moduleName;
                numberOfStudents[counter] = totalPurchase;

                counter++; 


            }

        }

    }

The above code doesn't work properly. When I try to print out an element of the array. it returns null for the string arrays and 0 for the int arrays suggesting that the code to read the data in isn't working.

Any suggestions or guidance much appreciated as it's getting frustrating at this point.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Java Coder
  • 11
  • 1
  • 1
  • 2

3 Answers3

1

The fact that only null's get printed suggests that the file doesn't exist or is empty (if you print it correctly).

It's a good idea to put in some checking to make sure everything is fine:

if (!file.exists())
  System.out.println("The file " + fileName + " doesn't exist!");

Or you can actually just skip the above and also take out the if (file.exists()) line in your code and let the FileNotFoundException get thrown.

Another problem is that next splits things by white-space (by default), the problem is that there is white-space on that second line.

nextLine should work:

String code = scan.nextLine();
String moduleName = scan.nextLine();
int totalPurchase = Integer.parseInt(scan.nextLine());

Or, changing the delimiter should also work: (with your code as is)

scan.useDelimiter("\\r?\\n");
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
  • Thanks for the reply, I added the check and it printed the error. My txt file is located in the project folder in eclpise so I don't understand why it's not working. – Java Coder Apr 18 '13 at 15:38
  • @JavaCoder [Two](http://stackoverflow.com/questions/681059/read-from-file-in-eclipse) [related](http://stackoverflow.com/questions/2792870/java-cant-find-file-when-running-through-eclipse) questions that may help you out. – Bernhard Barker Apr 18 '13 at 15:41
  • Still not working, It must be a problem with locating the file because I have tried all the code suggestions out and haven't had any success. – Java Coder Apr 18 '13 at 15:52
  • @JavaCoder I'm not too familiar with Eclipse and possible issues with it, I'll just point out that, as stated in one of those questions, it must be in the root directory of the project (in the same directory **where the `src` directory is**, but **not in** the `src` directory itself). Either way, using the [absolute path](http://www.computerhope.com/jargon/a/absopath.htm) for `fileName` should work. – Bernhard Barker Apr 18 '13 at 16:01
  • It's now is able to read from the file, It was giving an error saying input mismatch for the int value so I changed it to a string just to get it to work. (of course I'll need to get it working with the int eventually). Now it reads the strings into the arrays, however it only prints one word per line. If the module name is "Computer Architecture". It actually only reads in "Computer". – Java Coder Apr 18 '13 at 16:19
  • @JavaCoder Did you use my `nextLine` or `useDelimiter` suggestions? Either of these should fix both those problems. – Bernhard Barker Apr 18 '13 at 16:25
  • When I change the .next(); to .nextLine(); it gives the following error: Exception in thread "main" java.util.NoSuchElementException. I will try the other suggestion now. – Java Coder Apr 18 '13 at 16:28
  • I got it working now, it reads the full line now. I had to remove scan.next(); that another answer suggested and now it reads all words on a line. My only problem now is getting it to read the int value. – Java Coder Apr 18 '13 at 16:31
0
  String code = scan.nextLine();
  String moduleName = scan.nextLine();
  int totalPurchase = scan.nextInt();
  scan.nextLine()

This will move scanner to proper position after reading int.

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
  • Thanks for the reply, I added this to my code but it didn't seem to change anything. Still outputs "null" or "0" when I try to print elements of the arrays. – Java Coder Apr 18 '13 at 15:27
0

You are reading line so try this:

while(scan.hasNextLine()){
    String code = scan.nextLine();
    String moduleName = scan.nextLine();
    int totalPurchase = Integer.pasreInt(scan.nextLine().trim());

    moduleCodes[counter] = code;
    moduleNames[counter] = moduleName;
    numberOfStudents[counter] = totalPurchase;
    counter++; 
}
Achintya Jha
  • 12,735
  • 2
  • 27
  • 39