This semester we are going to write software for companies that sell products. You should decide on a product to sell and e-mail me with your choice. If someone else has chosen the same product, you will have to start over and come up with a different one. Keep sending me suggestions until your choice is unique. (I will only accept choices over e-mail, not in any other way.)
When you have decided upon a product, create a class that describes
it. The class should have 4 or 5 instance variables (fields), and
two of these should be a product ID and a name. For example, if your
product is fruit, some of the names might be apple, orange, pear, banana,
etc. The fields might be
String ID;
String name;
String variety;
double pricePerPound;
The class should have a constructor and several other methods including one to read the data from a file and another to display the data on the screen. The method that reads data in from a file should have a BufferedReader as a parameter.
public void readData (BufferedReader infile) throws IOException
{
ID = infile.readLine ();
name = infile.readLine ();
variety = infile.readLine ();
pricePerPound = Double.parseDouble (infile.readLine
());
} // readData
Create a file that contains a single product. It might look like
AD136
Apples
Red Delicious
1.50
Write a main class that reads in the data from the file and displays
it on the screen. You may refer to the example program on below.
Test your program to make sure that it reads and displays the data correctly.
Hand in a printout of your program together with a disk with the file and
the .java and .class files. Note: You may not have fruit as your
product choice.
import java.io.*;
// This application reads data in from a file and stores it in a class.
It then displays the data.
public class FruitSales
{
public static void main (String [] args)
{
try
{
BufferedReader infile = new BufferedReader (new InputStreamReader (new
FileInputStream ("fruit.txt")));
Fruit fruit = new Fruit ();
fruit.readData (infile);
fruit.displayData ();
} catch (IOException
e) {System.out.println ("File not found");}
} // main method
} // class FruitSales
// Class that describes a particular fruit.
class Fruit
{
String ID, name, variety;
double pricePerPound;
Fruit ()
{
ID = "";
name = "";
variety = "";
pricePerPound
= 0;
} // constructor
public void readData (BufferedReader infile)
throws IOException
{
ID = infile.readLine
();
name = infile.readLine
();
variety = infile.readLine
();
pricePerPound
= Double.parseDouble (infile.readLine ());
} // readData
public void displayData ()
{
System.out.println
("ID: " + ID);
System.out.println
("Name: " + name);
System.out.println
("Variety: " + variety);
System.out.println
("Price per pound: " + pricePerPound);
} // displayData
} // Fruit