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

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative