Thursday, 24 November 2016

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.

In this program, first we first create a class Student which have data members name, roll_no, sub1, sub2 and one method to read data here getdata( ) method and show the result here show( ) method. We have used java.io.BufferedReader class to read data from keyboard at runtime. Then we have created an object of Student class in StudentDemo class and called the methods of Student class.

When you compile the code using javac StudentDemo.java command two .class files will be created which are Student.class and StudentDemo.class, this has the advantage that you can reuse your .class file somewhere in other projects without compiling the code again. You can create as many classes as you want but writing many classes in a single file is not recommended as it makes code difficult to read rather you can create single file for every class. You can also group classes in packages for easily managing your code.

PROGRAM
import java.lang.*;
import java.io.*;

class Student {
 
 String name;
 int roll_no;
 int sub1,sub2;
 
 void getdata() throws IOException {
  
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println ("Enter Name of Student");
  name = br.readLine();
  
  System.out.println ("Enter Roll No. of Student");
  roll_no = Integer.parseInt(br.readLine());
  
  System.out.println ("Enter marks out of 100 of 1st subject");
  sub1 = Integer.parseInt(br.readLine());
  
  System.out.println ("Enter marks out of 100 of 2nd subject");
  sub2 = Integer.parseInt(br.readLine());
 }

 void show() {
  
  int total = sub1+sub2;
  float per = (total * 100) / 200;
  System.out.println ("Roll No. = "+roll_no);
  System.out.println ("Name = "+name);
  System.out.println ("Marks of 1st Subject = "+sub1);
  System.out.println ("Marks of 2nd Subject = "+sub2);
  System.out.println ("Total Marks = "+total);
  System.out.println ("Percentage = "+per+"%");
 }
}

public class StudentDemo {

 public static void main(String[] args) throws IOException {
  
  Student s=new Student();
  s.getdata();
  s.show();
 }
}
OUTPUT
C:\>javac StudentDemo.java
C:\>java StudentDemo
Enter Name of Student
Subhash Patel
Enter Roll No. of Student
13
Enter marks out of 100 of 1st subject
56
Enter marks out of 100 of 2nd subject
78
Roll No. = 13
Name = Subhash Patel
Marks of 1st Subject = 56
Marks of 2nd Subject = 78
Total Marks = 134
Percentage = 67.0%

No comments:

Post a Comment