Program to define a class Item containing code and price. Accept this data for five object using array of objects. Display code, price in tabular form and also, display total price of all items
This program demonstrates you the array of objects. Array of object is the collection of objects of the same class. The given syntax will define an array of reference therefore assign object to individual reference in the array to declare the array of object. The syntax to define array of object is:
<class-name> <array-name> [size];
For example, the following statement will define an array of object having size 6 references to the class Box.
Box b[6];
The above statement just declare array of objects. For creating an array of objects (allocating memory) you have to write down the following statements
for (int i=0; i<6; i++) {
b[i] = new Box( );
// Assigning object to individual reference in the array.
}
You can access the members of particular object by using membership operator like:
b[i].length = 10;
b[i].width = 20;
b[i].height = 30;
PROGRAMimport java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Item {
String code;
int price;
Item(String c,int p) {
code = c;
price = p;
}
public static void main(String args[])throws IOException
{
Item[] I = new Item[5];
String a;
int b,total_cost=0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for(int i=0;i<5;i++) {
System.out.print("Enter code for item"+(i+1)+" : ");
a = br.readLine();
System.out.print("Enter price for item"+(i+1)+" : ");
b = Integer.parseInt(br.readLine());
I[i] = new Item(a,b);
}
System.out.println("Item Code Item Price");
System.out.println("--------- ----------");
for(int i=0;i<5;i++)
{
System.out.print("\t"+I[i].code);
System.out.println("\t\t"+I[i].price);
total_cost = total_cost + I[i].price;
}
System.out.print("Total Price = "+total_cost);
}
}
OUTPUT
C:\>javac Item.java C:\>java Item Enter code for item1 : 101 Enter price for item1 : 54 Enter code for item2 : 102 6Enter price for item2 : 4 Enter code for item3 : 106 Enter price for item3 : 75 Enter code for item4 : 103 Enter price for item4 : 45 Enter code for item5 : 105 Enter price for item5 : 95 Item Code Item Price --------- ---------- 101 54 102 40 106 75 103 45 105 95 Total Price = 309