Sunday 11 June 2017

DBMS Tutorial-3


To Perform various data manipulation commands, aggregate functions and sorting concept on all created tables in previous tutorial.

Queries

  1. List total deposit from deposit.

    • select sum(amount)from deposit_gtu;
  2. List total loan from karolbagh branch

    • select sum(amount) from deposit_gtu where bname='Andheri';
  3. Give maximum loan from branch vrce.

    • select max(amount) from borrow_gtu where bname='VRCE';
  4. Count total number of customers.

    • select count(cname) from customers;
  5. Count total number of customer’s cities.

    • select count(DISTINCT city) from customers;
  6. Create table supplier from employee with all the columns.

    • create table supplier as select * from employee;
  7. Create table sup1 from employee with first two columns.

    • create table sup1 as (select * from employee WHERE EMP_NO<103 );
  8. Create table sup2 from employee with no data.

    • create table sup2 as select * from employee WHERE 1=2;
  9. Insert the data into sup2 from employee whose second character should be ‘n’ and string should be 5 characters long in employee name field.

    • INSERT INTO sup2 SELECT * FROM employee where emp_name like '_n___';
  10. Delete all the rows from sup1.

    • delete from sup1;
  11. Delete the detail of supplier whose sup_no is 103.

    • delete from supplier where emp_no=103;
Share:

DBMS Tutorial-2

  1. create table Job ( job_id varchar2 (15), job_title varchar2 (30) , min_sal number (7,2) , max_sal number (7,2));

    • insert into Job values('&job_id','&job_title','&min_sal','&max_sal');
  2. create table Employee (emp_no number (3), emp_name varchar2 (30), emp_sal number (8,2), emp_comm number (6,1), dept_no number (3));

    • insert into Employee values ('01','&emp_name','&emp_sal','&emp_comm','&dept_no');
  3. Create table deposit_gtu(a_no varchar2 (5),cname varchar2 (15),bname varchar2 (10),amount number (7,2), a_date date);

    • insert into deposit_gtu values('&a_no','&cname','&bname','&amount','&a_date');
  4. Create table borrow_gtu(loanno varchar2 (5),cname varchar2 (15),bname varchar2 (10),amount number (7,2));

    • insert into borrow_gtu values('&loanno','&cname','&bname','&amount');

Queries

  1. Retrieve all data from employee, jobs and deposit.

    • select * from Employee;
    • select * from Job;
    • select * from deposit_gtu;
  2. Give details of account no. and deposited rupees of customers having account opened between dates 01-01-06 and 25-07-06.

    • select ACTNO,AMOUNT from DEPOSIT where ADATE BETWEEN '01-JAN-06' and '25-JUL-03';
  3. Display all jobs with minimum salary is greater than 4000.

    • select * from Job where min_sal>4000;
  4. Display name and salary of employee whose department no is 20. Give alias name to name of employee.

    • select emp_name "name of employee",emp_sal "salary of employee" from employee where dept_no=20;
  5. Display employee no,name and department details of those employee whose department lies in(10,20)

    • select EMP_NO,EMP_NAME,DEPT_NO from EMPLOYEE where DEPT_NO BETWEEN 10 and 20;
Share:

Saturday 10 June 2017

DBMS Tutorial-1

  1. CREATE TABLE DEPOSIT (ACTNO VARCHAR2(5),CNAME VARCHAR2(18),BNAME VARCHAR2(18),AMOUNT NUMBER(8,2),ADATE DATE);

    • INSERT INTO DEPOSIT VALUES('&ACTNO','&CNAME','&BNAME','&AMOUNT','&ADATE');
  2. CREATE TABLE BRANCH(BNAME VARCHAR2(18),CITY VARCHAR2(18));

    • INSERT INTO BRANCH VALUES('&BNAME','&CITY');
  3. CREATE TABLE CUSTOMERS(CNAME VARCHAR2(19) ,CITY VARCHAR2(18));

    • INSERT INTO CUSTOMERS VALUES('&CNAME','&CITY');
  4. CREATE TABLE BORROW(LOANNO VARCHAR2(5), CNAME VARCHAR2(18), BNAME VARCHAR2(18), AMOUNT NUMBER (8,2));

    • INSERT INTO BORROW VALUES('&LOANNO','&CNAME','&BNAME','&AMOUNT');

Queries

  1. Describe deposit, branch.

    • desc deposit;
    • desc branch;
  2. Describe borrow, customers.

    • desc borrow;
    • desc customers;
  3. List all data from table DEPOSIT.

    • select * from deposit;
  4. List all data from table BORROW.

    • select * from borrow;
  5. List all data from table CUSTOMERS.

    • select * from customers;
  6. List all data from table BRANCH.

    • select * from branch;
  7. Give account no and amount of depositors.

    • select accno,amount from deposit;
  8. Give name of depositors having amount greater than 4000.

    • select cname from deposit where amount>4000;
  9. Give name of customers who opened account after date '1-12-96'

    • select cname from deposit where adate>'1-12-96';
Share:

Friday 9 June 2017

Sunday 4 June 2017

JAVA Tutorial-7

1. Write a Main method that takes the name of a text file as a command line argument and prints every line in lower case.

 
import java.io.*;
class Fileread
{
 public static void main(String s[])throws Exception
 {
  FileInputStream in =new FileInputStream(s[0]);
  int size=in.available();
  int i;
  char c;
  for(i=0;i<size;i++)
  {
   c=(char)in.read();
   System.out.print(Character.toLowerCase(c));
  }
  in.close();
 }
}

Output

2. Write a main() method that counts the number of words in a text file whose name is accepted from standard input. Also print the size of a file.

 
import java.util.*;
import java.io.*;
class Filecount
{
 public static void main(String s[])throws Exception
 {
  FileInputStream in =new FileInputStream(s[0]);
  Scanner sc=new Scanner(in);
  int size=in.available();
  int count=0;
  while(sc.hasNext())
  { 
   sc.next();
   count++;
  }
  System.out.println("Size of File: "+size);
  System.out.println("There are "+count+" Word in file");
  in.close();
 }
}

Output

3. Write a program using BufferedInputStream, FileInputStream, BufferedOutputStream, FileOutputStream to copy Content of one file File1.txt into another file File2.txt.


import java.io.*;
class Filecopy
{
 public static void main(String s[])throws Exception
 {
  FileInputStream in = new FileInputStream("File1.txt");
  BufferedInputStream bin = new BufferedInputStream(in);
  FileOutputStream ou = new FileOutputStream("File2.txt");
  BufferedOutputStream bou = new BufferedOutputStream(ou);
  int size=in.available();
  int i;
  for(i=0;i<size;i++)
  {
   bou.write((char)bin.read());
  }
  System.out.println("Content of one file is copied to another fle");
  bou.close();
  ou.close();
  bin.close();
  in.close();
 }
 
}

Output

Share:

Saturday 3 June 2017

JAVA Tutorial-6

1. Write a program to insert values into an array.
The user will enter a sequence of index and value to be stored at that index on the command line.
Define your exception handlers for the following cases:
Index is out of range.
Value < 0 and value > 5000.
Given index has already value stored.

 
class Exceptiondemo
{ 
 public static void main(String ar[])
 {
  int a[]=new int[Integer.parseInt(ar[0])];
  int i,j=2,k;
  try{
  
   for(i=1,k=0;i<ar.length;i+=2,k++)
   {
    a[Integer.parseInt(ar[i])]=Integer.parseInt(ar[j]);
    if(a[k]<0 || a[k]>5000)
    {
     throw new InvalidValueException();
    }
    j+=2;
   }
   for(i=0;i<a.length;i++)
   {
    System.out.println(a[i]);
   }
   
  }
  catch(ArrayIndexOutOfBoundsException e)
  {
   System.out.println("Array Index Out Of Bound Exception");
  }
  catch(InvalidValueException ex)
  {
   System.out.println(ex.toString());
  }
 }
} 
class InvalidValueException extends Exception
{
   public String toString()
   {
 return ("Invalid Value Exception / 0 value is already there in array");
   }  
}

Output

2. Write a program to get the date in form of DD MM YYYY from command line argument.
Raise and handle following custom exceptions to check the validity of the entered date.
 YearException: to check for valid four digit year.
 MonthException: to check whether the month is between 01 to 12 or not.
 DateException: to check wether date is between 01 to 31 or not.
It also checks the validity if date of month February when there is a leap year.

 
class YearException extends Exception
{
 YearException()
 {
  System.out.println("Year Exception Generated");
 }
 public String toString()
 {
  return "Invalid Year";
 }
}
class MonthException extends Exception
{
 MonthException()
 {
  System.out.println("Month Exception Generated");
 }
 public String toString()
 {
  return "Invalid Month";
 }
}
class DateException extends Exception
{
 DateException()
 {
  System.out.println("Date Exception Generated");
 }
 public String toString()
 {
  return "Invalid Date";
 }
}
class ddmmyyyy
{
   public static void main(String a[])
   {
 int yyyy=Integer.parseInt(a[2]);
 int mm=Integer.parseInt(a[1]);
 int dd=Integer.parseInt(a[0]);
 try
 {
  if(a.length==3)
  {
   //YEAR
   if(a[2].length()!=4 || yyyy<1000 || yyyy>9999)
   {
    throw new YearException();
   }
   else
   {
    System.out.println("Year: "+yyyy);
   }
   //MONTH
   if(a[1].length()!=2 || mm<01 || mm>12)
   {
    throw new MonthException();
   }
   else
   {
    System.out.println("Month: "+mm);
   }
   //DATE
   if(a[0].length()!=2)
   {
    throw new DateException();
   }
   else if(mm==01 || mm==03 || mm==05 || mm==07 || mm==8 || mm==10 || mm==12)
   {
    if(dd<01 || dd>31)
    {
     throw new DateException();
    }
    else
    {
     System.out.println("Date: "+dd);
    }
   }
   else if(mm==04 || mm==06 || mm==9 || mm==11)
   {
    if(dd<01 || dd>30)
    {
     throw new DateException();
    }
    else
    {
     System.out.println("Date: "+dd);
    }
   }
   else if(mm==02)
   {
    if((yyyy%4==0) && (yyyy%100!=0) || (yyyy%400==0))
    {
     if(dd<01 || dd>29)
     {
      throw new DateException();
     }
     else
     {
      System.out.println("Date: "+dd);
     }
    }
    else
    {
     if(dd<01 || dd>28)
     {
      throw new DateException();
     }
     else
     {
      System.out.println("Date: "+dd);
     }
    }
   }
  }
 }
 catch(YearException y)
 {
  System.out.println(y.toString());
 }
 catch(MonthException m)
 {
  System.out.println(m.toString());
 }
 catch(DateException d)
 {
  System.out.println(d.toString());
 }
   }
}

Output

3. Write a method for computing x & y by doing repetitive multiplication. x and y are of type integer and are to be given as command line arguments.
Raise and handle exception(s) for invalid values of x and y. Also define method main.


class InvalidNumberException extends Exception
{
 InvalidNumberException()
 {
  System.out.println("Power Is Negative ");
 }
}
class power
{
   public static void main(String a[])
   {
 int x=Integer.parseInt(a[0]);
 int y=Integer.parseInt(a[1]);
 int temp;
 try
 {
  if(y>=0)
  {
   if(y==0)
   {
    System.out.println(+x+" Power "+y+" is: "+1);
   }
   else
   {
    temp=x; 
    int i;
    for(i=1;i<y;i++)
    {
     temp=temp*x;
    }
    System.out.println(+x+" Power "+y+" is: "+temp);
   }
  }
  else if(y<0)
  {
   throw new InvalidNumberException();
  }
 }
 catch(InvalidNumberException i)
 {
  double temp1;
  int y1=(-y);
  temp1=1/(double)x;
  for(int j=1;j<y1;j++)
  {
   temp1=temp1*(1/(double)x);
  }
  System.out.println(+(double)x+" Power "+y+" is: "+temp1);
 }
   }
}

Output

4. Declare a class called coordinate to represent 3 dimensional Cartesian coordinates( x, y and z). Define following methods:
Constructors.
display method, to print values of members
add_coordinates method, to add three such coordinate objects to produce a resultant coordinate object.
Generate and handle exception if x, y and z coordinates of the result are zero.
main method, to show use of above methods.


class zerovalue extends Exception{}
class coordinate
{
 float x,y,z;
 coordinate()
 {
  x=0;
  y=0;
  z=0;
 }
 coordinate(float x,float y,float z)
 {
  this.x=x;
  this.y=y;
  this.z=z;
 }
 void display()
 {
  System.out.println("X: "+x);
  System.out.println("Y: "+y);
  System.out.println("Z: "+z);
 }
 void add_coordinates(coordinate obj1,coordinate obj2)
 {
  this.x=this.x+obj1.x+obj2.x;
  this.y=this.y+obj1.y+obj2.y;
  this.z=this.z+obj1.z+obj2.z;
 }
 public static void main(String args[])
 {
  coordinate c1=new coordinate(1,1,1);
  coordinate c2=new coordinate(2,2,2);
  coordinate c3=new coordinate(-3,3,3);
  c1.add_coordinates(c2,c3);
  coordinate c4=new coordinate();
  c4=c1;
  c4.display();
  try
  {
   if(c4.x==0||c4.y==0||c4.z==0)
   {
    throw new zerovalue();
   }
  }
  catch(zerovalue r)
  {
   System.out.println("Exception.No Co-Ordinate of Resultant Object Can Be Zero");
  }
 } 
}

Output

Share:

JAVA Tutorial-5

1. The abstract Vegetable class has three subclasses named Potato, Brinjal and Tomato.
Write an application that demonstrates how to establish this class hierarchy. Declare one instance variable of type String that indicates the color of a vegetable.
Create and display instances of these objects. Override the toString() method of Object to return a string with the name of the vegetable and its color

 
public abstract class Vegetable
{
 String color;
 public abstract String toString();
 public static void main(String a[])
 {
  Vegetable v=new Potato();
  System.out.println(v.toString());
  Vegetable v1=new Brinjal();
  System.out.println(v1.toString());
  Vegetable v2=new Tomato();
  System.out.println(v2);
 }
}
class Potato extends Vegetable
{
 Potato()
 {
  color="white Potato";
 }
 public String toString()
 {
  return("Color of Potato: "+this.color);
 }
}
class Brinjal extends Vegetable
{
 Brinjal()
 {
  color="dark purple";
 }
 public String toString()
 {
  return("Color of Brinjal: "+this.color);
 }
}
class Tomato extends Vegetable
{
 Tomato()
 {
  color="Red";
 }
 public String toString()
 {
  return("Color of Tomato: "+this.color);
 }
}

Output

2. The Transport interface declares a deliver() method.
The abstract class Animal is the superclass of the Tiger, Camel, Deer and Donkey classes.
The Transport interface is implemented by the Camel and Donkey classes.
Write a test program that initialize an array of four Animal objects.
If the object implements the Transport interface, the deliver() method is invoked

 
interface Transport
{
 public void deliver();
}
abstract class Animal
{
 public void show()
 {
  
 }
}
class Tiger extends Animal
{
 public void show()
 {
  System.out.println("I am in show method of Animal class overrided in Tiger class ");
 }
}
class Camel extends Animal implements Transport
{
 public void deliver()
 {
   System.out.println("I am in deliver method of Transport Interface overrided in Camel class ");
 }
}
class Deer extends Animal
{
 public void show()
 {
   System.out.println("I am in show method of Animal class overrided in Deer class ");
 }
 
}
class Donkey extends Animal implements Transport
{
 public void deliver()
 {
   System.out.println("I am in deliver method of Transport Interface overrided in Donkey class ");
 }
 
}
class AnimalDemo
{
   public static void main(String args[])
   {
 Animal A[]=new Animal[4];
 A[0]=new Tiger();
 A[1]=new Camel();
 A[2]=new Deer();
 A[3]=new Donkey();
 if(A[0] instanceof Transport)
 {
  ((Transport)A[0]).deliver();
 }
 else
 {
  A[0].show();
 }
 if(A[1] instanceof Transport)
 {
  ((Transport)A[1]).deliver();
 }
 else
 {
  A[1].show();
 }
 if(A[2] instanceof Transport)
 {
  ((Transport)A[2]).deliver();
 }
 else
 {
  A[2].show();
 }
 if(A[3] instanceof Transport)
 {
  ((Transport)A[3]).deliver();
 }
 else
 {
  A[3].show();
 }
   }
}

Output

3. Describe abstract class called Shape which has three subclasses say Triangle,Rectangle,Circle.
Define one method area() in the abstract class and override this area() in these three subclasses to calculate for specific object
i.e. area() of Triangle subclass should calculate area of triangle etc. Same for Rectangle and Circle.


public abstract class Shape
{
 public void area()
 {
 }
 public static void main(String a[])
 {
  Shape s;
  s=new Triangle(30,20);
  s.area();
  s=new Rectangle(10,10);
  s.area();
  s=new Circle(20);
  s.area();
 }
}
class Triangle extends Shape
{
 double h,b;
 Triangle(double he,double ba)
 {
  h=he;
  b=ba;
 }
 public void area()
 {
  System.out.println("Area of Triangle is:"+(h*b)/2);
 }
}
class Rectangle extends Shape
{
 int h,l;
 Rectangle(int h,int l)
 {
  this.h=h;
  this.l=l;
 }
 public void area()
 {
  System.out.println("Area of Recangle is:"+(h*l));
 }
}
class Circle extends Shape
{
 double r;
 Circle(double r)
 {
  this.r=r;
 }
 public void area()
 {
  System.out.println("Area of Circle is:"+(3.14*r*r));
 }
}

Output

4. Write a program that illustrates interface inheritance. Interface P is extended by P1 and P2.
Interface P12 inherits from both P1 and P2. Each interface declares one constant and one method. Class Q implements P12.
Instantiate Q and invoke each of its methods. Each method displays one of the constants.


interface p
{
 public int p=10;
 public void p();
}
interface p1 extends p
{
 public int p1=20;
 public void p1();
}
interface p2 extends p
{
 public int p2=30;
 public void p2();
}
interface p12 extends p1,p2
{
 public int p12=40;
 public void p12();
}
public class Q implements p12
{
 public void p()
 {
  System.out.println("Value of P is: "+p);
 }
 public void p1()
 {
  System.out.println("Value of P1 is: "+p1);
 }
 public void p2()
 {
  System.out.println("Value of P2 is: "+p2);
 }
 public void p12()
 {
  System.out.println("Value of P12 is: "+p12);
 }
 public static void main(String a[])
 {
  Q obj=new Q();
  obj.p();
  obj.p1();
  obj.p2();
  obj.p12();
 }
}

Output

5. Declare a class called employee having employee_id and employee_name as members.
Extend class employee to have a subclass called salary having designation and monthly_salary as members. Define following:
  • Required constructors
  • A method to find and display all details of employees drawing salary more than Rs. 20000/-
  • Method main for creating an array for storing these details given as command line arguments and showing usage of above methods.


import java.util.Scanner;
class employee
{
 int emp_id;
 String emp_name;
 employee(int id,String name)
 {
  emp_id=id;
  emp_name=name;
 }
}
class Salary extends employee
{
 String designation;
 double emp_salary;
 Salary(int id,String name,String deg,double sal)
 {
  super(id,name);
  designation=deg;
  emp_salary=sal;
 }
 void display()
 {
  System.out.println("Employee Id: "+this.emp_id);
  System.out.println("Employee Name: "+this.emp_name);
  System.out.println("Employee Designation: "+this.designation);
  System.out.println("Employee Salary: "+this.emp_salary);
 }
 public static void main(String a[])
 {
  int n,i,id;
  String name,deg;
  double sal;
  Scanner sc=new Scanner(System.in);
  n=Integer.parseInt(a[0]);
  Salary s[]=new Salary[n];
  System.out.println("Enter "+n+" employee entry");
  for(i=0;i<n;i++)
  {
   System.out.print("\nEnter employee name: " );
   name=sc.next();
   System.out.print("\nEnter employee Designation: ");
   deg=sc.next();
   System.out.print("\nEnter employee Salary: ");
   sal=sc.nextDouble();
   System.out.print("\nEnter employee id: ");
   id=sc.nextInt();
   s[i]=new Salary(id,name,deg,sal);
   System.out.println("");
  }
  for(i=0;i<n;i++)
  {
   if(s[i].emp_salary>20000)
   {
    s[i].display();
   }
  }
 }
}

Output

6. Declare a class called book having author_name as private data member.
Extend book class to have two sub classes called book_publication & paper_publication.
Each of these classes have private member called title.
Write a complete program to show usage of dynamic method dispatch (dynamic polymorphism) to display book or paper publications of given author.
Use command line arguments for inputting data.


class book
{
 private String author_name;
 book(String author)
 {
  author_name=author;
 }
 void display()
 {
  System.out.println("Author name: "+this.author_name);
 }
}
class book_publication extends book
{
 private String book_title;
 book_publication(String name,String title)
 {
  super(name);
  book_title=title;
 }
 void display()
 {
  super.display();
  System.out.println("Book name: "+book_title);
 }
}

class paper_publication extends book
{
 private String paper_title;
 paper_publication(String name,String title)
 {
  super(name);
  paper_title=title;
 }
 void display()
 {
  super.display();
  System.out.println("paper name: "+paper_title);
 }
}
class bookdemo
{
 public static void main(String a[])
 {
  book b;
  String ba,book,pa,p;
  ba=a[0];
  book=a[1];
  pa=a[2];
  p=a[3];
  book_publication bo=new book_publication(a[0],a[1]);
  paper_publication po=new paper_publication(a[2],a[3]);
  b=bo;
  b.display();
  b=po;
  b.display();
 }
}

Output

Share:

Friday 2 June 2017

JAVA Tutorial-4

1. create a class called student having data member like name,enr,branch,city,spi define construct which can ini data member
define method for follwing func
get()
disp()

 
import java.util.Scanner;
class Student
{
 int enr;
 String name,city,branch;
 double spi;
 Student()
 {
  enr=123;
  name="sam";
  city="Surat";
  branch="computer";
  spi=7.21;
 }
 void get()
 {
  Scanner sc=new Scanner(System.in);
  System.out.print("\nEnter the Student Name: ");
  name=sc.nextLine();
  System.out.print("\nEnter the Student Branch: ");
  branch=sc.nextLine();
  System.out.print("\nEnter the Student City: ");
  city=sc.nextLine();
  System.out.print("\nEnter the Student Enrollement no: ");
  enr=sc.nextInt();
  System.out.print("\nEnter the Student SPI: ");
  spi=sc.nextDouble();
 }
 void display()
 {
  System.out.println("Student Enrollement: "+enr);
  System.out.println("Student Name: "+name);
  System.out.println("Student Branch: "+branch);
  System.out.println("Student City: "+city);
  System.out.println("Student SPI: "+spi);
 }
 public static void main(String ar[])
 {
  Student std=new Student();
  std.get();
  std.display();
 }
}

Output

2. It is required to compute SPI (semester performance index) of n students of your college for their registered subjects in a semester. Declare a class called student having following data members: id_no ,no_of_subjects_registered ,subject_code , subject_credits ,grade_obtained and spi.
  • Define constructor and calculate_spi methods.
  • Define main to instantiate an array for objects of class student to process data of n students to be inputted through keyboard.

 
import java.util.Scanner;
class Studentspi
{
 int id_no;
 int subject_code[]={36001,36002,36003,36004};
 int subject_credit[]={5,6,8,4};
 String grade[]=new String[4];
 int marks=0;
 double spi;
 String sub[]={"ADA","SP","JAVA","MPI"};
 Studentspi()
 {
  Scanner s1=new Scanner(System.in);
  int i;
  System.out.print("Enter Student IDNO:");
  this.id_no=s1.nextInt();
  for(i=0;i<4;i++)
  {
   System.out.print("Enter grade of "+sub[i]+": ");
   this.grade[i]=s1.next();
   if(this.grade[i].equals("aa"))
   {
    this.marks=this.marks+(100*subject_credit[i]);  
   }
   else if(this.grade[i].equals("ab"))
   {
    this.marks=this.marks+(90*subject_credit[i]);  
   }
   else if(this.grade[i].equals("bb"))
   {
    this.marks=this.marks+(80*subject_credit[i]);  
   }
   else if(this.grade[i].equals("bc"))
   {
    this.marks=this.marks+(70*subject_credit[i]);
   }
   else if(this.grade[i].equals("cc"))
   {
    this.marks=this.marks+(60*subject_credit[i]);
   }
   else if(this.grade[i].equals("cd"))
   {
    this.marks=this.marks+(50*subject_credit[i]);
   }
   else if(this.grade[i].equals("dd"))
   {
    this.marks=this.marks+(40*subject_credit[i]);
   }
  }
 }
 void calculate_spi()
 {
  
  this.spi=(this.marks/23)/10; 
  System.out.println("Student Id_no:"+this.id_no);
  System.out.println("");
  System.out.println("Subject_code  Subject  Subject_Credit  Grade"); 
  for(int i=0;i<4;i++)
  {
   System.out.println("    "+this.subject_code[i]+"       "+this.sub[i]+"       "+this.subject_credit[i]+"           
                        "+this.grade[i]); 
  }
  System.out.println("\nSPI is"+this.spi);
  System.out.println("");
 }
 public static void main(String str[])
 {
  Scanner sca=new Scanner(System.in);
  int n,i;
  System.out.print("Enter the how many Student? ");
  n=sca.nextInt();
  Studentspi st[]=new Studentspi[n];
  for(i=0;i<n;i++)
  {
   st[i]=new Studentspi();
  }
  for(i=0;i<n;i++)
  {
   st[i].calculate_spi();   
  }
 }
}

Output

3. Define the Rectangle class that contains: Two double fields x and y that specify the center of the rectangle, the data field width and height , A no-arg constructor that creates the default rectangle with (0,0) for (x,y) and 1 for both width and height.
  • A parameterized constructor creates a rectangle with the specified x, y, height and width.
  • A method getArea() that returns the area of the rectangle.
  • A method getPerimeter() that returns the perimeter of the rectangle.
  • A method contains(double x, double y) that returns true if the specified point(x,y) is inside this rectangle.
Write a test program that creates two rectangle objects. One with default valuesand other with user specified values. Test all the methods of the class for boththe objects.


class Rectangle
{
 double x,y,width,height;
 Rectangle()
 {
  x=0;
  y=0;
  width=1;
  height=1;
 }
 Rectangle(double x,double y,double w,double h)
 {
  this.x=x;
  this.y=y;
  this.width=w;
  this.height=h;
 }
 double getArea()
 {
  return (this.width*this.height);
 }
 double getperimeter()
 {
  return (2*(this.width+this.height));
  
 }
 boolean contains(double p,double q)
 {
  double x1,x2,x3,x4,y1,y2,y3,y4;
  x1=x4=(this.x-(this.width/2));
  x2=x3=(this.x+(this.width/2));
  y1=y2=(this.y-(this.height/2));
  y3=y4=(this.y+(this.height/2));
  if((p>=x1 && p<=x2) && (q>=y1 && q<=y3))
  {
   return true;
  }
  else
  {
   return false;
  }
 }
}
class RectangleMain
{
 public static void main(String a[])
 {
  Rectangle ract1=new Rectangle();
  System.out.println("Area of Rectangle is: "+ract1.getArea());
  System.out.println("Perimeter of Rectangle is: "+ract1.getperimeter());
  System.out.println("(x,y) Cordinates is Inside in Rectangle? \n Ans: "+ract1.contains(10,10));
  
  Rectangle ract2=new Rectangle(50,50,30,20);
  System.out.println("Area of Rectangle is: "+ract2.getArea());
  System.out.println("Perimeter of Rectangle is: "+ract2.getperimeter());
  System.out.println("(x,y) Cordinates is Inside in Rectangle? \n Ans: "+ract2.contains(40,90));

 }
}

Output

4. Create a new class called “City” that can be used to keep track of location information for a given city. Your class should include the following – be sure to comment your class appropriately:
a. String name
b. double lon (for longitude)
c. double lat (for latitude)
d. A constructor that accepts a name, lon and lat value and stores them in the instance variables for the object
e. A method that reports the current position of a city. Here is a method header to get you started:
public void report()
f. A method that computes the distance from the lon and lat of one city to the lon and lat of another city. Use the standard distance formula to compute this value (let’s pretend that the cities lie on a flat plane and not on a sphere!) Here’s a method header to get you started:
public double distanceFrom(City otherCity)
Create a new class called “Program4”. Do the following in this class:
a. Create an instance of City with name=Rajkot, lon=70.802160, lat=22.303894.
b. Create another instance of City with name=Surat, lon=72.831061, lat=21.170240.
c. Create another instance of City with name=Mumbai, lon=72.877656, lat=19.075984.


class City
{
 String name;
 double lon,lat;
 City(String name,double lo,double la)
 {
  this.name=name;
  this.lon=lo;
  this.lat=la;
 }
 void report()
 {
  System.out.println("City: "+this.name);
  System.out.println("Longitude: "+this.lon);
  System.out.println("Latitude: "+this.lat);
 }
 double distanceFrom(City othercity)
 {
  double R=6371;
  double dlon = deg2rad(othercity.lat - this.lat); 
  double dlat = deg2rad(othercity.lon - this.lon);
  double a = Math.pow((Math.sin(dlat/2)),2) + Math.cos(deg2rad(this.lat)) * Math.cos(deg2rad(othercity.lat)) * 
                Math.pow((Math.sin(dlon/2)),2);
  double c = 2 * Math.atan2( Math.sqrt(a), Math.sqrt(1-a) );
  double d = R * c;// (where R is the radius of the Earth)
  return d;
 }
 double deg2rad(double d)
 {
   return d * (Math.PI/180);
 }
}
class CityDemo
{
 public static void main(String a[])
 {
  City c1=new City("Rajkot",70.8021599,22.3038945);
  c1.report();
  City c2=new City("Surat",72.8310607,21.1702401);
  c2.report();
  System.out.println("Distance Between "+c1.name+" and "+c2.name+" "+c1.distanceFrom(c2)+" KM");
  City c3=new City("Mumbai",72.877656,19.075984);
  c2.report();
  System.out.println("Distance Between "+c1.name+" and "+c3.name+" "+c1.distanceFrom(c3)+" KM");    
 }
}

Output

5. Design a class named Fan to represent a fan. The class contains: - Three constants named SLOW, MEDIUM and FAST with values 1,2 and 3 to denote the fan speed.
  • An int data field named speed that specifies the speed of the fan (default SLOW).
  • A boolean data field named f_on that specifies whether the fan is on(default false).
  • A double data field named radius that specifies the radius of the fan (default 4).
  • A data field named color that specifies the color of the fan (default blue).
  • A no-arg constructor that creates a default fan.
  • A parameterized constructor initializes the fan objects to given values.
  • A method named display() will display description for the fan. If the fan is on, the display() method displays speed, color and radius. If the fan is not on, the method returns fan color and radius along with the message “fan is off.
  • Write a test program that creates two Fan objects. One with default values and the other with medium speed, radius 6, color brown, and turned on status true.
  • Display the descriptions for two created Fan objects.


class Fan
{
 final int slow=1,medium=2,fast=3;
 int speed;
 boolean f_on;
 double radius;
 String color;
 Fan()
 {
  speed=slow;
  f_on=false;
  radius=4;
  color="blue";
 }
 Fan(int sp,boolean fon,double r,String co)
 {
  speed=sp;
  f_on=fon;
  radius=r;
  color=co;
 }
 void display()
 {
  if(this.f_on==false)
  {
   System.out.println("\nFan is 'OFF' ");
   System.out.println("Fan Color: "+this.color);
   System.out.println("Fan Radius: "+this.radius);
   System.out.println("");
  }
  else
  { 
   System.out.println("Fan is 'ON'");
   System.out.println("Fan Speed: "+this.speed);
   System.out.println("Fan Color: "+this.color);
   System.out.println("Fan Radius: "+this.radius);
  }
 }
}
class FanDemo
{
 public static void main(String args[])
 {
  Fan f1=new Fan();
  Fan f2=new Fan(f1.medium,true,6,"brown");
  f1.display();
  f2.display();
 }
}

Output

Share:

JAVA Tutorial-3

  1. Create an array of String variables and initialize the array with the names of the months from January to December. Create an array containing 12 random decimal values between 0.0 and 100.0. Display the names of each month along with the corresponding decimal value. Calculate and display the average of the 12 decimal values.
  2. Write a program to accept a line and check how many consonants and vowels are there in line.
  3. Write a program to find length of string and print second half of the string.
  4. Write a program to find that given number or string is palindrome or not.
  5. Write a program that sets up a String variable containing a paragraph of text of your choice. Extract the words from the text and sort them into alphabetical order.
    Display the sorted list of words. Also count the number of words that start with capital letters. You could use a simple sorting method called the bubble sort.
    To sort an array into ascending order the process is as follows:
    a. Starting with the first element in the array, compare successive elements (0 and 1, 1 and 2, 2 and 3, and so on).
    b. If the first element of any pair is greater than the second, interchange the two elements.
    c. Repeat the process for the whole array until no interchanges are necessary. The array elements will now be in ascending order.
  6. Create a class which ask the user to enter a sentence, and it should display count of each vowel type in the sentence. The program should continue till user enters a word quit. Display the total count of each vowel for all sentences.

1. Create an array of String variables and initialize the array with the names of the months from January to December. Create an array containing 12 random decimal values between 0.0 and 100.0. Display the names of each month along with the corresponding decimal value. Calculate and display the average of the 12 decimal values.

 
class Month
{
   public static void main(String a[])
   {
 String[] mon={"January","Febuary","March","April","May","June","July","August","september","October","November","December"}; 
 int i;
 double sum=0; 
 double n[]=new double[12];
 System.out.println("Random number");
 for(i=0;i<12;i++)
 {
  n[i]=((100.00*Math.random())+1);
 }
 for(i=0;i<12;i++)
 {
  System.out.print(+n[i]+".");
  System.out.println(mon[i]);
  sum=sum+n[i];
 }  
 System.out.println("Sum of 12 number :"+sum); 
 System.out.println("Average :"+(sum/12));
   }
}

Output

2. Write a program to accept a line and check how many consonants and vowels are there in line.

 
class Consonants
{
   public static void main(String a[])
   {
 String s=a[0];
 int l=(int)(s.length()),i,vcnt=0,ccnt=0;
 for(i=0;i<l;i++)
 {
  char c=s.charAt(i);
  if(c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || c=='A' || c=='E' || c=='I' || c=='O' || c=='U')
   vcnt++;
  else
   ccnt++;
 }
 System.out.println("Total Vowels :"+vcnt);
 System.out.println("Total Constants :"+ccnt);
   }
}

Output

3. Write a program to find length of string and print second half of the string.

 
import java.util.Scanner;
class SecondHalfStr
{
   public static void main(String str[])
   {
 System.out.print("Enter a String: ");
 Scanner sc=new Scanner(System.in);
 String st=sc.nextLine();
        System.out.println("Full String Length: "+st.length());
 String st1=st.substring((st.length())/2);
 System.out.println("Half of the String are: "+st1);
   }
}

Output

4. Write a program to find that given number or string is palindrome or not.

 
import java.util.Scanner;
class Palindrome
{
   public static void main(String str[])
   {
 Scanner sc=new Scanner(System.in);
 int ch=0;
 while(ch!=3)
 {
  System.out.println("\n1.Number");
  System.out.println("2.String"); 
  System.out.println("3.Exit");
  System.out.print("Enter your Choice to Print 'PALINDROME' or not :");
  ch=sc.nextInt();
  switch(ch)
  {
   case 1:
   System.out.println("Enter Numbers :");
   int no=sc.nextInt(); 
   int temp=no,rev=0;
   while(temp!=0)
   {
    rev = rev * 10;
    rev = rev + temp%10;
    temp = temp/10;
   }
   if(rev==no)
   {
    System.out.println(rev+" Number is 'PALINDROME'");
   }
   else
   {
           System.out.println(rev+" Number is not 'PALINDROME'");
   }
      break;
    case 2:
   System.out.print("\nEnter String :");
   String s=sc.next();
   String s2="";
   for(int i=(s.length())-1;i>=0;i--)
   {
    s2=s2+s.charAt(i);
   }
   if(s==s2)
   {
    System.out.println(s+" String is not 'PALINDROME'");
   }
   else
   {
    System.out.println(s+" String is 'PALINDROME'");
   }
   break;
                        case 3:
                                ch=3;
                        break;
   default:
   System.out.println("Invalid Choice");
   break;
  }
 }
   }
}

Output

5. Write a program that sets up a String variable containing a paragraph of text of your choice. Extract the words from the text and sort them into alphabetical order.
Display the sorted list of words. Also count the number of words that start with capital letters. You could use a simple sorting method called the bubble sort.
To sort an array into ascending order the process is as follows:
a. Starting with the first element in the array, compare successive elements (0 and 1, 1 and 2, 2 and 3, and so on).
b. If the first element of any pair is greater than the second, interchange the two elements.
c. Repeat the process for the whole array until no interchanges are necessary. The array elements will now be in ascending order.

 
import java.util.Scanner;
class Splitstring
{
 String s;
 String st[];
 int count=0;
 Splitstring(String str)
 {
  s=str;
 }
 void splitsort()
 {
  int i;
  st=s.split(" ");
  for(i=0;i<(st.length)-1;i++)
  {
   for(int j=0;j<(st.length)-1;j++)
   {
    if(st[j].compareTo(st[j+1])>0)
    { 
     String temp=st[j];
     st[j]=st[j+1];
     st[j+1]=temp;
    }
   } 
  }
  for(i=0;i<(st.length);i++)
  {
   if(st[i].charAt(0)>=64 && st[i].charAt(0)<=90)
   {
    count++;
   }
  }
 }
 void display()
 {
  System.out.println("Sorted Array");
  for(int i=0;i<(st.length);i++)
  {
   System.out.println(st[i]);
  }
  System.out.println("Start with capital Alphabet in array: "+count);
 }
 public static void main(String str[])
 {
  Scanner sc=new Scanner(System.in);
  String a;
  System.out.print("Enter tthe String: ");
  a=sc.nextLine();
  Splitstring spl=new Splitstring(a);
  spl.splitsort();
  spl.display();
 }
}

Output

6. Create a class which ask the user to enter a sentence, and it should display count of each vowel type in the sentence. The program should continue till user enters a word quit. Display the total count of each vowel for all sentences

 
import java.util.Scanner;
class AskUserDemo
{
 String st;
 int vo[]=new int[5];
 void str()
 {
  Scanner sc=new Scanner(System.in);
  while(true)
  {
   System.out.println("Enter the Sentence: ");
   st=sc.nextLine();
   if(st.equals("quit"))
   {
    break;
   }
   else
   {
    for(int i=0;i<(st.length());i++)
    {
     if(st.charAt(i)=='a' || st.charAt(i)=='A')
     {
      vo[0]++;
     }
     else if(st.charAt(i)=='e' || st.charAt(i)=='E')
     {
      vo[1]++;
     }
     else if(st.charAt(i)=='i' || st.charAt(i)=='I')
     {
      vo[2]++;
     }
     else if(st.charAt(i)=='o' || st.charAt(i)=='O')
     {
      vo[3]++;
     }
     else if(st.charAt(i)=='u' || st.charAt(i)=='U')
     {
      vo[4]++;
     }
    }
   }
   System.out.println("a or A is "+vo[0]+" times");
   System.out.println("e or E is "+vo[1]+" times");
   System.out.println("i or I is "+vo[2]+" times");
   System.out.println("o or O is "+vo[3]+" times"); 
   System.out.println("u or U is "+vo[4]+" times");
  }
 }
 public static void main(String str[])
 {
  AskUserDemo as=new AskUserDemo();
  as.str();
 }
}

Output

Share:

Thursday 1 June 2017

JAVA Tutorial-2

  1. Write a program to display a random choice from a set of six choices for breakfast (you could use any set; for example, scrambled eggs, waffles, fruit, cereal, toast, or yogurt).
  2. When testing whether an integer is a prime, it is sufficient to try to divide by integers up to the square root of the number being tested. Write a program to use this approach.
  3. A lottery requires that you select six different numbers from the integers 1 to 49. Write a program to do this for you and generate five sets of entries.
  4. Write a program to generate a random sequence of capital letters that does not include vowels.
  5. Write an interactive program to print a string entrered in a pyramid form. For instance, the string “stream” has to be displayed as follows:
    S
    S t
    S t r
    S t r e
    S t r e a
    S t r e a m
  6. Write an interactive program to print a diamond shape. For example, if user enters the number 3, the diamond will be as follows:
        *
       * *
      * * *
       * *
        *
       ...
    

1. Write a program to display a random choice from a set of six choices for breakfast (you could use any set; for example, scrambled eggs, waffles, fruit, cereal, toast, or yogurt).

 
import java.util.Random;
class choice
{
   public static void main(String args[])
   {
	Random randomGenerator = new Random();
	int r;
	r=randomGenerator.nextInt(6);
	System.out.println("random number="+r);
	System.out.println("1.scrambled eggs");
	System.out.println("2.waffles");
	System.out.println("3.fruit");
	System.out.println("4.cereal");
	System.out.println("5.toast");
	System.out.println("6.yogurt");
	switch(r)
	{
		case 1:
		  System.out.print("Your Choiced Value Is= scrambled eggs");
		break;
		case 2:
		  System.out.print("Your Choiced Value Is= waffles");
		break;
		case 3:
		  System.out.print("Your Choiced Value Is= furit");
		break;
		case 4:
		  System.out.print("Your Choiced Value Is= cereal");
		break;
		case 5:
		  System.out.print("Your Choiced Value Is= toast");
		break;
		case 6:
		  System.out.print("Your Choiced Value Is= Yogurt");
		break;
		default:
		  System.out.println("Invalid Choice");
		break;
	}
   }
}

Output

2. When testing whether an integer is a prime, it is sufficient to try to divide by integers up to the square root of the number being tested. Write a program to use this approach.

 
import java.util.Scanner;
class primeno
{
   public static void main(String ar[])
   {
	int n,sq,f=0,i;
	Scanner s=new Scanner(System.in);
	System.out.print("Enter a number to find wheather this number is prime number or not: ");
	n=s.nextInt();
	sq=(int)(Math.sqrt(n));
	for(i=sq;i<n;i++)
	{
		if((n%i)==0)
		{
			f=1;
			break;
		}
	}
	if(f==1)
	{
		System.out.println(+n+" is not prime number");
	}
	else
	{
		System.out.println(+n+" is prime number");
	}
   }
}

Output

3. A lottery requires that you select six different numbers from the integers 1 to 49. Write a program to do this for you and generate five sets of entries.

 
class lottery
{
   public static void main(String ar[])
   {
	int lucky,i,f=0;
	int a[]=new int[6];
	System.out.println("Ticket No");
	for(i=0;i<6;i++)
	{
		a[i]=(int)((6*Math.random())+1);
	}
	lucky=(int)((49*Math.random())+1);
	for(i=0;i<6;i++)
	{
		System.out.println(+a[i]);
	}	
	System.out.println("Lucky Number: "+lucky);
	for(i=0;i<6;i++)
	{
		if(a[i]==lucky)
		{
			f=1;
			break;
		}
	}
	if(f==1)
	{
		System.out.println(+lucky+" no ticket is winner");	
	}
	else
	{
		System.out.println("Sorry today no one is winner");
	}
   }
}

Output

4. Write a program to generate a random sequence of capital letters that does not include vowels.

 
import java.util.Random;
class vowels
{
   public static void main(String a[])
   {
	int i;
	Random r = new Random();
	char c[] = new char[5]; 
	for(i=0;i<5;i++)
	{
		c[i]=(char)(r.nextInt(26) + 'A');
	}
	for(i=0;i<5;i++)
	{ 
		switch(c[i])
		{
			case 'A':
			  System.out.println("Sorry this letter is vowel");
			break;
			case 'E':
			  System.out.println("Sorry this letter is vowel");
			break;
			case 'I':
			  System.out.println("Sorry this letter is vowel");
			break;
			case 'O':
			  System.out.println("Sorry this letter is vowel");
			break;
			case 'U':
			  System.out.println("Sorry this letter is vowel");
			break;
			default:
 			  System.out.println(c[i]);
   			break;
		}
	}
   }
}

Output

5. Write an interactive program to print a string entrered in a pyramid form. For instance, the string “stream” has to be displayed as follows:
S
S t
S t r
S t r e
S t r e a
S t r e a m

 
import java.io.*;
class pyramid
{
   public static void main(String a[])
   {
	char ch[]={'s','t','r','e','a','m'};
	String s=new String(ch);
	int i,j,k,n;
	n=s.length();
	for(i=n;i>0;i--)
	{
	        j=0;
		for(k=i;k<=n;k++)
		{
			System.out.print(ch[j]);
			System.out.print(" ");
			j++;
		}
		System.out.println("");
	}	
   }
}

Output

6. Write an interactive program to print a diamond shape. For example, if user enters the number 3, the diamond will be as follows:
    *
   * *
  * * *
   * *
    *
   ...

 
class diamond
{
   public static void main(String a[])
   {
	int i,j,k,n;
	n=Integer.parseInt(a[0]);
	for(i=n;i>0;i--)
	{
		for(j=0;j<i;j++)
		{
			System.out.print(" ");
		}
		j=0;
		for(k=i;k<=n;k++)
		{
			System.out.print("*");
			System.out.print(" ");
			j++;
		}
		System.out.println("");
	}
	for(i=n-1;i>0;i--)
	{
		for(j=i;j<=n;j++)
		{
			System.out.print(" ");
		}
		j=0;
		for(k=i;k>0;k--)
		{
			System.out.print("*");
			System.out.print(" ");
			j++;
		}
		System.out.println("");
	}
   }
}

Output

Share:

JAVA Tutorial-1

1. Demonstrate HelloWorld Application with Single and Multiple Main in a java program.

 
   class Hello
   {
     public static void main(String a[])
     {
       System.out.println("Hello Java");
       main();
     }
     public static void main()
     {
       System.out.println("Hello World");
     } 
   }

Output

2. Write a console program to define and initialize a variable of type byte to 1, and then successively multiply it by 2 and display its value 8 times. Explain the reason for the last result.

 
class ByteDemo
{
   public static void main(String ar[])
   {
      byte a=1;
      int i=1;
      while(i<=8)
      { 
         a=(byte)(a*2);
  System.out.println(a);
  i++;
       }
   }
}

Output

Reason : Byte range is -128 to 127, so in this case 64*2=128 but byte range upto 127 so it will starts from -128 that's why last two output is -128 and 0

3. Write a program that defines a floating-point variable initialized with a dollar value for your income and a second floating-point variable initialized with a value corresponding to a tax rate of 35 percent. Calculate and output the amount of tax you must pay with the Rs. and paisa stored as separate integer values (use two variables of type int to hold the tax, perhaps taxRs and taxPaisa).

 
class tax
{
   public static void main(String args[])
   {
 float a,b,rs;
 int taxrs,taxpaisa,t;
 a=(float)200.85;
 b=(float)((35.00*a)/100.00);
 rs=(float)(b*67.50);
 taxrs=(int)rs;
 taxpaisa=(int)((rs-taxrs)*100);
 System.out.println("Tax Rate in Dollars="+b);
 System.out.println("Tax Rate in Rs="+taxrs);
 System.out.println("Tax Rate in Paisa="+taxpaisa);
   }
}

Output

4. Write a program that calculate percentage marks of the student if marks of 6 subjects are given.

 
class marks
{
   public static void main(String args[])
   {
 int ma=50,java=60,mp=66,sp=65,ada=65,dbms=70;
 float per;
 System.out.println("Subject Marks");
 System.out.println("Math="+ma);
 System.out.println("java="+java);
 System.out.println("mp="+mp);
 System.out.println("sp="+sp);
 System.out.println("ada="+ada);
 System.out.println("dbms="+dbms);
 per=(float)(((ma+java+mp+sp+ada+dbms)*100)/600);
 System.out.println("Percentage="+per);
   }
}

Output

Share: