Reputation: 627
I have a file that I put some numbers into but then I decided I wanted to label the numbers with a name for each one, like so:
A = 1 2 3
B = 3 4 5
C = 6 7 8
This caused an exception to be thrown. I want to know how I can workaround this so the scanner 'ignores' all but the numbers unless I tell it otherwise.
Can anyone help?
EDIT:
Also, I already know what is causing the exception. I am using next.Double(); to pick out the numbers in the file.
public static void readFile() throws IOException, FileNotFoundException {
String fileName = "vectors.txt";
// Reference the file using the the BufferedReader object
BufferedReader input = new BufferedReader(new FileReader(fileName));
//scanner to scan through file
Scanner token = new Scanner(input);
double fileX = token.nextDouble();
double fileY = token.nextDouble();
double fileZ = token.nextDouble();
vecA = new Vector3D(fileX,fileY,fileZ);
fileX = token.nextDouble();
fileY= token.nextDouble();
fileZ = token.nextDouble();
vecB = new Vector3D(fileX, fileY, fileZ);
fileX = token.nextDouble();
fileY= token.nextDouble();
fileZ = token.nextDouble();
//initialize vecC using double values from third line of file
vecC = new Vector3D(fileX, fileY, fileZ);
//close file
input.close();
}
Upvotes: 1
Views: 886
Reputation: 726479
You cannot make the scanner ignore input automatically, but you can write code to skip input yourself until you see that a double is available:
while (!scanner.hasNextDouble()) {
scanner.next();
}
double d = scanner.nextDouble();
If you need to put this code in multiple places, you can wrap it in a function:
private static double skipAndGetDouble(Scanner scanner) {
while (scanner.hasNext() && !scanner.hasNextDouble()) {
scanner.next();
}
return scanner.hasNextDouble() ? scanner.nextDouble() : Double.NaN;
}
Upvotes: 3
Reputation: 285405
You need to parse the text that makes sense for the data being scanned. So in your case, you have lines that repeat the basic type of information held -- meaning use a loop -- don't repeat code unnecessarily. In pseudocode
create a Scanner object read the file, say called fileScanner
while still lines to be read (fileScanner.hasNextLine())
read line with fileScanner using .nextLine()
Create a new Scanner object, lineScanner to get tokens in line.
Use lineScanner to get `next` String via `.next()` and store
Use lineScanner to get `next` String via `.next()` (the `=`) and ignore
Use lineScanner to get 3 doubles.
close line scanner
Store all info in object and place in ArrayList or some other collection
end while
close fileScanner
Upvotes: 0