/** * ParseLines.java * @author Jeff Ondich, 29 October 2010 * * A demonstration of the use of a Scanner to read an input * file one line at a time, and another Scanner to parse data * from the line. * * The data file read by this program is expected to have lines * of the form: * * Lovelace 1815 1852 * Babbage 1791 1871 * Turing 1912 1954 * * etc. That is, a string (containing no spaces) and two integers * separated by spaces. */ import java.io.*; import java.util.*; public class ParseLines { public static void main(String args[]) { if (args.length != 1) { System.err.println("Usage: java ReadLines fileName"); System.exit(1); } Scanner fileScanner = null; try { fileScanner = new Scanner(new File(args[0])); } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } int lineNumber = 0; while (fileScanner.hasNextLine()) { String line = fileScanner.nextLine(); lineNumber++; // Now that you have the line, there are lots // of ways to get the string and two integers // out of it. Here's one ugly approach. String name; int birthYear, deathYear; Scanner lineScanner = new Scanner(line); if (lineScanner.hasNext()) { name = lineScanner.next(); if (lineScanner.hasNextInt()) { birthYear = lineScanner.nextInt(); if (lineScanner.hasNextInt()) { deathYear = lineScanner.nextInt(); System.out.println(name + "'s age at death: " + (deathYear - birthYear)); continue; } } } System.out.println("Malformed input line #" + lineNumber + ": " + line); } } }