Program to read records from file "stud.dat" and calculate total and percentage

Here, we read the details of students from file and display the total marks and percentage of each student on console. The DataInputStream class is used in the context of DataOutputStream and can be used to read primitives. Following is the constructor to create an InputStream:
DataInputStream  in  =  DataInputStream (InputStream  in);

PROGRAM
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;

class ReadRecordFromFile {

 public static void main(String[] args) {

  try
  {
   File f=new File("stud.dat");
   FileInputStream fos=new FileInputStream(f);
   DataInputStream dos=new DataInputStream(fos);
   
   int roll_no,m1,m2,tot;
   float per;
   String name;
   
   System.out.println("Roll No  Name M1 M2 Total Percent");
   for(int i=1; i<=3; i++)
   {
    roll_no = dos.readInt();
    name = dos.readUTF();
    m1 = dos.readInt();
    m2 = dos.readInt();
    tot=m1+m2;
    per=tot/2.0f;
    System.out.printf(" %d    %s   %d  %d  %d   %.2f\n",roll_no,name,m1,m2,tot,per);
   }
   dos.close();
  }
  catch(Exception ee){
   System.out.println(ee);
  }
 }

}
OUTPUT
C:\>javac ReadRecordFromFile.java
C:\>java ReadRecordFromFile
Roll No  Name M1 M2 Total Percent
 4     Rohan   75  87  162   81.00
 5     Darshan   65  70  135   67.50
 8     Subhash   61  49  110   55.00

Comments

Popular posts from this blog

Develop an Android application to display “Hello World!” on screen

Program to design an applet which draws a circle (having color BLUE) inside a triangle (having color YELLOW)

Build a Simple Android App to Display Student Details