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

  1. When I first started programming for Java these tasks seemed to be a quite difficult. Now, it's quite easy. For those who deal with Dat files, I would advise to get up the solutions how to open .dat file https://wikiext.com/dat and take advantage of the universal file viewer that was tested by me and applied in practice for a lot of file formats.

    ReplyDelete

Post a Comment

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.

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

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.