I have a .txt file with lines of this format example : torch ; 3.0 ; 23.0
I want to scan it in order to place the first item in a String, and the second and third in a float.
Here is what I have done so far but the scan.skip(" ; ")
doesn't work, I have also tried scan.skip(Pattern.compile(" ; ")
but it didn't work either.
File file = new File(dir);
try {
Scanner scan = new Scanner(file);
scan.skip(" ; ");
scan.useDelimiter(Pattern.compile(" ; "));
while (scan.hasNextLine()) {
String s = scan.next();
float f1 = scan.nextFloat();
float f2 = scan.nextFloat();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Do you have any solutions for me ? Thanks
You may use ;
or \n
as delimiter and no need to skip, also I'd suggest to use Float.parseFloat(scan.next());
Scanner scan = new Scanner(file);
scan.useDelimiter(Pattern.compile("[;\\n]"));
while (scan.hasNextLine()) {
String s = scan.next();
float f1 = Float.parseFloat(scan.next());
float f2 = Float.parseFloat(scan.next());
System.out.println(s + " " + f1 + " " + f2);
}