I am having an extremely difficult time splitting each line from the text file into an array of strings and using it like I need to. The split() seems to work okay. I end up having an array of strings, where the first slot of the strings array contains a number that I need to parse as an int, to continue my code. For some reason, I keep getting the error shown below that I can’t seem to figure out.
My goal is it to simply store every line of the text file that contains letters, in an array, and parse the number which is going to be the first value of the line, as an integer. Once I accomplish this, I need to be able to use every preceding group of letters independently, so I am trying to get those in an array as well.
I appreciate any help with this.
Many thanks in advance!
NOTE: numGrammars is the first number shown on the first line of the text file.
My Code
numGrammars = Integer.parseInt(fin.next());
System.out.println("Num Grammars:" + numGrammars);
for(int v=0; v < numGrammars; v++){
int numVariables = Integer.parseInt(fin.next());
System.out.printf("numVariables: %s", numVariables);
for(int z=0; z < numVariables; z++){
//reads in variable line
String line = fin.nextLine();
String[] strings = line.split(" ");
for(int m=0; m < strings.length; m++){
int numRules = Integer.parseInt(strings[0]);
//All other array slots in strings array should be groups of letters on group per slot...
}
}
}
Console Output
Num Grammars:2
numVariables: 3Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Methods.readFile(Methods.java:34)
at Main.main(Main.java:12)
Text file I am reading from:
1
3
2 S AB BB
3 A BB a b
2 B b c
Only use
fin.nextLine(). After the call tonext(), the cursor is right after the numVariables value3, but before the newline. When you callnextLine()after that, it returns everything between the cursor and the newline, which is an empty string! UsingnextLine()each time always places the cursor after the newline, and everything is OK.