Java Reference
In-Depth Information
water, 1.00
orange juice, 2.50
milk, 3.20
bread, 1.11
2.
Create a new class called ShowGroceries . First of all, you will take a look at how you would read
out the grocery list and show it without using a Scanner :
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ShowGroceries {
public static void main(String[] args) {
try (
BufferedReader in = new BufferedReader(new FileReader(
"grocerieswithprices.txt"));
) {
String line;
while ((line = in.readLine()) != null) {
String[] splittedLine = line.split(", ");
String item = splittedLine[0].trim();
double price = Double.parseDouble(splittedLine[1].trim());
System.out.format("Price of %s is: %.2f%n", item, price);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.
This approach works fine for simple cases, but depending on the nature and structure of your input
text, you might want to resort to a Scanner instead, as follows:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Locale;
import java.util.Scanner;
import java.util.regex.Pattern;
public class ShowGroceries {
public static void main(String[] args) {
try (
Scanner sc = new Scanner(
new FileReader("grocerieswithprices.txt"));
) {
sc.useDelimiter(Pattern.compile("(, )|(\r\n)"));
sc.useLocale(Locale.ENGLISH);
while (sc.hasNext()) {
String item = sc.next();
Search WWH ::




Custom Search