Reputation: 511
while(scan.hasNext()){
String line = scan.next();
String[] tempArray = line.split(",\\s*");
for (int i=0; i<3; i++){
System.out.println(tempArray[i]);
}
My input file looks like:
A, 0, 3
C, 2, 2
BB, 3, 3
DA, -3, 0
ED, 2, -2
It returns A, then gives me an error. What gives?
Upvotes: 0
Views: 82
Reputation: 3019
String line = scan.next();
For your input file, the first time you access this, line
will be equal to "A,"
, which is not what you wanted.
This is because Scanner#next()
only reads up until a whitespace character, which is present in the input file between A,
and 0,
. Hence, why only A,
is returned.
Instead use
String line = scan.nextLine();
Which will read up until a line break. So the first loop will set line
to "A, 0, 3"
.
Debugging can really help improve programming abilities. Printing out the return of line
to see what is being processed could have definitely helped with this. Being able to then figure out what is happening to produce those results is a lot easier.
Upvotes: 0
Reputation: 201439
I would split on comma and then trim()
the String
,
while(scan.hasNextLine()){ // <-- hasNextLine()
String line = scan.nextLine(); // <-- nextLine()
String[] tempArray = line.split(","); // <-- split on the comma.
for (int i=0; i<tempArray.length; i++){ // <-- use the array length
System.out.println(tempArray[i].trim()); // <-- trim() the String
}
}
Upvotes: 1