How to read data from a text file into arrays in Java -


i having trouble programming assignment. need read data txt file , store in parallel arrays. txt file contents formatted this:

line1: stringwith466numbers line2: string few words line3(int): 4 line4: stringwith4643numbers line5: string few words line6(int): 9 

note: "line1: ", "line2: ", etc display purposes , isn't in txt file.

as can see goes in pattern of threes. each entry txt file 3 lines, 2 strings , 1 int.

i read first line array, second another, , third int array. fourth line added first array, 5th line second array , 6th line third array.

i have tried write code can't 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 try print out element of array. returns null string arrays , 0 int arrays suggesting code read data in isn't working.

any suggestions or guidance appreciated it's getting frustrating @ point.

the fact null's printed suggests file doesn't exist or empty (if print correctly).

it's idea put in checking make sure fine:

if (!file.exists())   system.out.println("the file " + filename + " doesn't exist!"); 

or can skip above , take out if (file.exists()) line in code , let filenotfoundexception thrown.

another problem next splits things white-space (by default), problem there white-space on second line.

nextline should work:

string code = scan.nextline(); string modulename = scan.nextline(); int totalpurchase = integer.parseint(scan.nextline()); 

or, changing delimiter should work: (with code is)

scan.usedelimiter("\\r?\\n"); 

Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -