I have a formatted text file that I need to extract information from and put into corresponding member variables in a class Item (1 line of text = 1 Item).
I am using Scanner and delimiter, but it can only recognize the ;
separating information and not new lines.
I've tried a few different regex expressions and my latest one is down below where I specify only the delimiter I know is coming up. I've also tried the regex [;\\n]
. My only conclusion is that scanner treats new line characters different than other (which kind of makes sense, I know it has functions based on new lines).
Here is the text file format
1000;Knock Bits;88;12.67;8015
1001;Widgets;10;35.50;8004
1002;Grommets;20;23.45;8001
and here is what my code looks like
while (scan.hasNext())
{
Item item = new Item();
scan.useDelimiter("[;]");
item.setID(scan.nextInt());
item.setName(scan.next());
item.setQuantity(scan.nextInt());
item.setPriceInCents((int) scan.nextFloat()*100);
scan.useDelimiter("\\n");
item.setSupplierID(scan.nextInt());
}
All the above code works except the last line getting supplierID with nextInt()
. I know I could just replace that line with
item.setSupplierID(Integer.parseInt(scan.nextLine()));
But that's kind of ugly and there should be a way to do it using regex without having to customize a line specifically for the last word. Preferably using only one delimiter for the whole loop.