Friday, April 11, 2008

Read a File

Write a program that reads and properly parses a file called "people.txt" which contains the name of the person followed by his age and then his height in feet. A sample file looks like:

Mario 34 4.5
Donkey Kong 15 5.7
Luigi 38 5.8
Princess Peach Toadstoll 25 5.2

A very easy question. You need to remember how to loop to read a file and, more importantly, that this data should go into a record or class. Since each row represents a person, a good programmer should initially default to thinking about each row as an object with various attributes.

The only tricky part in this example is the fact that a person's name could be any number of words. Thus, we have to look for the first integer before we can declare that the complete name has been found.

import java.util.Scanner;

public class Person {
private String name;
private int age;
private double height;

public Person (Scanner in){
name = "";
while (!in.hasNextInt()){
name += + " ";
age = in.nextInt();
height = in.nextDouble();

public String toString(){
return name + " " + age + " " + height;

public static void main (String[] args){
String filename = "people.txt";
try {
Scanner in = new Scanner(new File(filename));
while (in.hasNextLine()){
Person p = new Person(in);
} catch (FileNotFoundException e){
System.out.println("Sorry, could not find file " + e);

No comments: