E-book of Practical Assignments 2007-08
Transcript of E-book of Practical Assignments 2007-08
BBAACCHHEELLOORR IINN CCOOMMPPUUTTEERR SSCCIIEENNCCEE ((HHOONNSS.. ))
PPRRAACCTTIICCAALL AASSSSIIGGNNMMEENNTTSS OONN
MMIICCRROOPPRROOCCEESSSSOORR AANNDD AASSSSEEMMBBLLYY LLAANNGGUUAAGGEE PPRROOGGRRAAMMMMIINNGG,,
OOBBJJEECCTT OORRIIEENNTTEEDD PPRROOGGRRAAMMMMIINNGG ((CC++++ && JJAAVVAA)) AANNDD DDAATTAABBAASSEE MMAANNAAGGEEMMEENNTT SSYYSSTTEEMM
((PPaappeerr--VVIIII))
SSuubbmmiitt tteedd bbyy
RRaajjiibb NNaatthh
TTDDCC PPaarrtt--IIII
SSeessssiioonn:: 22000077--0088
RRoollll:: SS--220088 NNoo..:: 22002222332255
RReeggiissttrraattiioonn NNoo..:: 1100220011880055 ooff 22000066--22000077
DDeeppaarrttmmeenntt ooff CCoommppuutteerr SScciieennccee
KKaarriimmggaannjj CCoolllleeggee
KKaarriimmggaannjj
Object Oriented Programming (C++ & JAVA) and Database Management System Index
Object Oriented Programming (C++) Date of Submission : 11/10/2007 Page 1 – 77 Assignment-01: Calculating the sum of a series 2 - 4 Assignment-02: Multiplying two matrices 5 - 8 Assignment-03: Transfer the contents of one file to another 9 -12 Assignment-04: Calculating the sum of digits of a number 13-15 Assignment-05: Addition and Subtraction of COMPLEX objects 16-19 Assignment-06: Copying selective records from one file to another 20-23 Assignment-07: Calculating the roots of a quadratic equation 24-27 Assignment-08: Adding two matrices 28-31 Assignment-09: Displaying numbers in a structured manner 32-34 Assignment-10: Adding two POLAR objects 35-37 Assignment-11: Computing area of figures (using ‘virtual functions’) 38-41 Assignment-12: Computing electricity bills for units consumed 42-44 Assignment-13: Designing a system for maintaining a book shop 45-50 Assignment-14: Designing a system for maintaining bank accounts 51-58 Assignment-15: Designing an employee database (using a class network) 59-64 Assignment-16: Implementing a menu driven phonebook (using a file) 65-70 Assignment-17: Finding minimum value in an array (using function template) 71-73 Assignment-18: Implementing Bubble sort technique (using function template) 74-77 Object Oriented Programming (Java) Date of Submission : 24/01/2008 Page 78 -146 Assignment-01: Checking whether two strings are equal or not 79-80 Assignment-02: Displaying the reverse of a string 81-82 Assignment-03: Calculating the sum of digits of a given number 83-84 Assignment-04: Displaying a multiplication table 85-86 Assignment-05: Displaying all prime numbers between two numbers 87-88 Assignment-06: Sorting an existing array 89-91 Assignment-07: Checking all the Math class function 92-94 Assignment-08: Finding the number of words and lines in a file 95-96 Assignment-09: Implementing a system for maintaining bank accounts 97-105 Assignment-10: Implementing the use of overloading and overriding methods 106-107 Assignment-11: Implementing multiple inheritance using interfaces 108-110 Assignment-12: Creating a student’s report card (using packages) 111-114 Assignment-13: Implementing the various methods of the Thread class 115-118 Assignment-14: Implementing the concept of Runnable interface 119-120 Assignment-15: Creating and throwing an exception 121-122 Assignment-16: Appending names to a file already containing a few names 123-125 Assignment-17: Concatenating and buffering of files 126-127 Assignment-18: Creating a sequential file to store details of five products 128-130 Assignment-19: Updating the previous sequential file using random access 131-133 Assignment-20: Creating a text field to accept only numeric values of fixed length 134-135 Assignment-21: An applet program for finding the largest of three numbers 136-138 Assignment-22: Creating a Frame with checkboxes to change colour at runtime 139-141 Assignment-23: Creating an RGB colour by taking R, G, B values from three scrolls 142-143 Assignment-24: Demonstrating the implementation of a Choice and Label in a Frame 144-146 SQL Assignments (Assignment# 01 to Assignment# 36) Page 147 -176
PPRRAACCTTIICCAALL AASSSSIIGGNNMMEENNTTSS
OOBBJJEECCTT OORRIIEENNTTEEDD PPRROOGGRRAAMMMMIINNGG ((JJAAVVAA))
78
TTOOOOLLSS,, PPLLAATTFFOORRMM,, LLAANNGGUUAAGGEE AANNDD HHAARRDDWWAARREE UUSSEEDD
Machine type: IBM Think Centre
CPU type: Pentium 4
Co-processor: Installed
CPU clock: 2.8 GHz
RAM: 256 MB
Display type: VGA mono and upward compatibility
Hard disk: 40 GB
Floppy disk: 1.44 MB
Operating System: Microsoft Windows XP Professional
Language: Java
Compiler: Javac
79
Object Oriented Programming (Java) Practical Assignment - 01
Write a Java program to check whether two strings are equal or not.
80
CODING:
//Java assignment module 01
import java.lang.String.*; //importing lang.String class
class EqString{ //class definition strated
public static void main(String args[ ]){
if(args.length<2){
System.out.println("Too few parameters.");
System.exit(1);
}
if(args.length>2){
System.out.println("Too many parameters.");
System.exit(1);
}
if(args[0].equals(args[1])) //checking equality of strings
System.out.println("The two strings are equal.");
else
System.out.println("The two strings are unequal.");
}
}
OUTPUT:
C:\Java files>java EqString madam Madam
The two strings are unequal.
C:\Java files>java EqString College College
The two strings are equal.
81
Object Oriented Programming (Java) Practical Assignment - 02
Write a Java program to display reverse of a string.
82
CODING:
//Java assignment module 02
import java.io.*; //import statements
import java.lang.*;
class StringRev
{ public static void main(String[ ] args)
{ if (args.length>1)
{
System.out.println("Too many parameters. Only 1 parameter expected.");
System.exit(1);
}
StringBuilder str= new StringBuilder(); //StringBuilder object created
try{ str.append(args[0]); }
catch(ArrayIndexOutOfBoundsException out)
{ System.out.println("Too few parameters. 1 parameter expected.");
System.exit(1);
}
str.reverse(); //a function of StringBuilder class being called
System.out.println("The reversed string is : "+str);
}
}
OUTPUT:
C:\Java files>java StringRev
Too few parameters. 1 parameter expected.
C:\Java files>java StringRev Dot saw I was tod
Too many parameters. Only 1 parameter expected.
C:\Java files>java StringRev "Dot saw I was tod"
The reversed string is : dot saw I was toD
83
Object Oriented Programming (Java) Practical Assignment - 03
Write a Java program to find the sum of digits of a given number.
84
CODING: //Java assignment module 03 import java.lang.*; class SumOfDigits { public static void main(String args[ ]) { if (args.length>1) { System.out.println("Too many parameters. Only 1 parameter expected."); System.exit(1); } int num=0; int dig=0; int sum=0; try { num=Integer.parseInt(args[0]); int number=num; for(;number>0;dig=number%10,sum=sum+dig, number=number/10); System.out.println("The sum of digits of "+num+" is "+sum); } catch(ArrayIndexOutOfBoundsException out) { System.out.println("Too few parameters. 1 parameter expected."); System.exit(1); } catch(NumberFormatException numx) { System.out.println("Integer expected as argument."); System.exit(1); } finally { System.out.println("Thank you."); System.exit(1); } } }
OUTPUT: C:\Java files>java SumOfDigits Too few parameters. 1 parameter expected. C:\Java files>java SumOfDigits 123.456 Integer expected as argument. C:\Java files>java SumOfDigits 123456 The sum of digits of 123456 is 21 Thank you.
85
Object Oriented Programming (Java) Practical Assignment - 04
Write a Java program to display a multiplication table.
86
CODING:
//Java assignment module 04
class mulTab
{
public static void main(String args[ ])
{
int twoD[ ][ ]=new int[10][10];
int i=0; int j=0;
System.out.println("MULTIPLICATION TABLE FOR '5 X 10'");
for(i=1;i<=5;i++)
for(j=1;j<=10;j++) //nested ‘for’ loops
twoD[j-1][i-1]=i*j;
for (i=0;i<10;i++)
{
for (j=0;j<5;j++)
System.out.printf(“%2d “,twoD[i][j]); //printing multiplication table
System.out.println( );
}
}
}
OUTPUT:
MULTIPLICATION TABLE FOR '5 X 10' 1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
6 12 18 24 30
7 14 21 28 35
8 16 24 32 40
9 18 27 36 45
10 20 30 40 50
87
Object Oriented Programming (Java) Practical Assignment - 05
Write a Java program to display all prime numbers between two given numbers.
88
CODING: //Java assignment module 05 import java.lang.*; class ShowPrimes { public static void main(String args[ ]) { try { if (args.length>2) { System.out.println("Too many parameters. Only 2 parameters expected."); System.exit(1); } int num=Integer.parseInt(args[0]); int max=Integer.parseInt(args[1]); int factor=2; for(;num<=max;num++) { for(factor=2;factor<num;factor++) { if(num%factor==0) break; } if(factor==num) System.out.print(num+", "); } } catch(ArrayIndexOutOfBoundsException outx) { System.out.println("Too few parameters. 2 parameters expected."); System.exit(1); } catch(NumberFormatException numx) { System.out.println("Integer expected as argument."); System.exit(1); } finally { System.out.println("\nThank you."); System.exit(1); } } }
OUTPUT: C:\Java files>java ShowPrimes 47.32 Integer expected as argument. C:\Java files>java ShowPrimes 100 Too few parameters. 2 parameters expected. C:\Java files>java ShowPrimes Too few parameters. 2 parameters expected. C:\Java files>java ShowPrimes 1 100 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 Thank you.
89
Object Oriented Programming (Java) Practical Assignment - 06
Write a Java program to sort an existing array.
90
CODING:
//Java assignment module 06
import java.io.*;
class sortName
{
public static void main(String args[ ])
{
System.out.println("Program for sorting names of students.");
System.out.print("Enter the number of students. ");
BufferedReader streamIn=new BufferedReader(new InputStreamReader(System.in));
int n=0;
try
{
n=Integer.parseInt(streamIn.readLine());}
catch(Exception e)
{ }
String array[ ]=new String[n];
String temp;
int i=0; int j=0;
System.out.println("Enter the "+n+" name(s) one by one.");
try{
for (i=0;i<n;i++)
{
array[i]=streamIn.readLine();
}
}
catch(Exception e)
{ }
for(i=0;i<array.length;i++)
for (j=0;j<array.length-i-1;j++)
91
if(array[j].compareTo(array[j+1])>0)
{
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
System.out.println("\nThe names in sorted order are:");
for(i=0;i<array.length;i++)
System.out.println(array[i]);
}
}
OUTPUT:
Program for sorting names of students.
Enter the number of students. 4
Enter the 4 name(s) one by one.
Debojit
Tanushree
Amit
Rajeev
The names in sorted order are:
Amit
Debojit
Rajeev
Tanushree
92
Object Oriented Programming (Java) Practical Assignment - 07
Write a Java program to check all the math class function.
93
CODING: //Java assignment module 07 import java.io.*;
class MathDemo{
public static void main(String[ ] args) throws IOException{
BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
System.out.println("This java program is for demonstrating Math class methods.");
System.out.print("Enter a decimal value: ");
double a=Double.parseDouble(buf.readLine());
System.out.printf("The absolute value of %.3f is %.3f%n", a, Math.abs(a));
System.out.printf("The ceiling of %.2f is %.0f%n", a, Math.ceil(a));
System.out.printf("The floor of %.2f is %.0f%n", a, Math.floor(a));
System.out.printf("The rint of %.2f is %.0f%n", a, Math.rint(a));
System.out.printf("exp(%.3f) is %.3f%n", a, Math.exp(a));
System.out.printf("log(%.3f) is %.3f%n", a, Math.log(a));
System.out.print("Enter any two numbers: ");
a=Double.parseDouble(buf.readLine());
double b=Double.parseDouble(buf.readLine());
System.out.printf("pow(%.3f, %.3f) is %.3f%n", a, b, Math.pow(a, b));
System.out.printf("sqrt(%.3f) is %.3f%n", a, Math.sqrt(a));
System.out.printf("sqrt(%.3f) is %.3f%n", b, Math.sqrt(b));
System.out.print("Enter a value in degrees: ");
a=Double.parseDouble(buf.readLine());
b=Math.toRadians(a);
System.out.format("The sine of %.1f degrees is %.4f%n", a,
Math.sin(b));
System.out.format("The cosine of %.1f degrees is %.4f%n", a,
Math.cos(b));
System.out.format("The tangent of %.1f degrees is %.4f%n", a,
Math.tan(b));
System.out.format("The arcsine of %.4f is %.4f degrees %n",
Math.sin(b),
Math.toDegrees(Math.asin(Math.sin(b))));
System.out.format("The arccosine of %.4f is %.4f degrees %n",
Math.cos(b),
Math.toDegrees(Math.acos(Math.cos(b))));
System.out.format("The arctangent of %.4f is %.4f degrees %n",
Math.tan(b),
Math.toDegrees(Math.atan(Math.tan(b))));
94
System.out.print("Enter any two integer numbers: ");
int c=Integer.parseInt(buf.readLine());
int d=Integer.parseInt(buf.readLine());
System.out.printf("The max of %d and %d is %d%n",c, d, Math.max(c, d));
System.out.printf("The min of of %d and %d is %d%n",c, d, Math.min(c, d));
System.out.println("A random number: "+(int)(Math.random() * 10));
}
}
OUTPUT:
This java program is for demonstrating Math class methods.
Enter a decimal value: 45.683
The absolute value of 45.683 is 45.683
The ceiling of 45.68 is 46
The floor of 45.68 is 45
The rint of 45.68 is 46
exp(45.683) is 69163158283712220000.000
log(45.683) is 3.822
Enter any two numbers: 21.62
4.31
pow(21.620, 4.310) is 566536.666
sqrt(21.620) is 4.650
sqrt(4.310) is 2.076
Enter a value in degrees: 45
The sine of 45.0 degrees is 0.7071
The cosine of 45.0 degrees is 0.7071
The tangent of 45.0 degrees is 1.0000
The arcsine of 0.7071 is 45.0000 degrees
The arccosine of 0.7071 is 45.0000 degrees
The arctangent of 1.0000 is 45.0000 degrees
Enter any two integer numbers: 15
13
The max of 15 and 13 is 15
The min of of 15 and 13 is 13
A random number: 3
95
Object Oriented Programming (Java) Practical Assignment - 08
Write a Java program to display number of words and lines in a file.
96
CODING: //Java assignment module 08 import java.lang.*; import java.io.*; import java.util.*; class CountTokens{ public static void main(String args[ ]) throws IOException{ int cntWord=0; int cntLine=0; String str; StringTokenizer st; BufferedReader inStream=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter filename: "); str=inStream.readLine(); inStream=new BufferedReader(new FileReader(str)); while((str=inStream.readLine())!=null){ cntLine++; st=new StringTokenizer(str," ,;?:.!"); while(st.hasMoreTokens()) { cntWord++; st.nextToken(); } } System.out.println("Word Count : "+cntWord); System.out.println("Line Count : "+cntLine); inStream.close(); } }
OUTPUT: C:\Java files>java CountTokens Enter filename: MyFile.txt Word Count : 33 Line Count : 3 Contents of “MyFile.txt” This program is for counting words and lines of text in a file. Some text is taken from the user and entered into the file. Then the program performs counting and displays result.
97
Object Oriented Programming (Java) Practical Assignment - 09
Assume that a bank maintains two kinds of accounts for customers, one called as
savings account and the other as current account. The savings account provides
compound interest and withdrawal facilities but no cheque book facility. The
current account provides cheque book facility but no interest. Current account
holders should also maintain a minimum balance and if the balance falls below
this level, a service charge is imposed.
Create a class account that stores customer name, account number and type of
account. From this derive the classes’ cur_acct and sav_acct to make them more
specific to their requirements. Include necessary member functions in order to
achieve the following tasks:
Accept deposit from a customer and update the balance.
Display the balance.
Compute and deposit interest.
Permit withdrawal and update the balance.
Check for the minimum balance, impose penalty, necessary and update the balance.
Include constructors for all the three classes.
98
CODING: //File Account.java defined inside subdirectory "pax" package pax; import java.io.*; import java.lang.*; public abstract class Account { public static final float MIN_S=200.00F; public static final float MIN_C=450.00F; public static final float SERVIC=15.00F; public static BufferedReader inStream=new BufferedReader(new InputStreamReader(System.in)); String name, acctNo; protected double balance; char mode; public Account(){ name=new String(); acctNo=new String(); balance=0.0F; mode=' '; } public Account(String name, String acct, double initBal, char type){ this.name=new String(name); acctNo=new String(acct); balance=initBal; mode=type; } public void showStatus(){ System.out.println("Account number: "+acctNo); System.out.println("Account holder: "+name); System.out.printf("Current balance: Rs. %.2f\n",balance); } public boolean matchAcctNo(String acct){ return(acctNo.equalsIgnoreCase(acct)); } public void showBal(){ System.out.printf("Current balance: Rs. %.2f",balance); } abstract public void deposit(double amnt)throws IOException; abstract public void withdraw()throws IOException; } //Java assignment module 09 (File BankService.java) import java.io.*; import java.lang.*; import pax.Account; import static java.lang.Math.*; class SavAccount extends Account { static final char type='s';
99
SavAccount(String name, String acct, double initBal){ super(name, acct, 0.0F, type); deposit(initBal); } public void withdraw()throws IOException { System.out.print("Enter withdrawal slip number: "); inStream.readLine(); System.out.print("Enter the amount to be withdrawn: Rs."); float amnt=Float.valueOf(inStream.readLine()).floatValue(); char ch; if(amnt>balance) System.out.println("Withdrawal request denied. Account balance insufficient."); else{ if(balance-amnt<MIN_S){ System.out.println("Remaining balance will be less than Rs."+MIN_S+", the minimum
balance. "); System.out.println("Service charge of Rs."+SERVIC+" will be deducted from account
balance. "); System.out.print("Continue withdrawing? (Y/N) ");
switch(ch=inStream.readLine().charAt(0)){ case 'y': case 'Y':balance=balance-(amnt+SERVIC); System.out.println("Rs."+amnt+" withdrawn successfully."); break; default: System.out.println("Withdrawal process aborted."); } } else{ balance=balance-amnt; System.out.println("Rs."+amnt+" withdrawn successfully."); } showBal();
} } public void deposit(double amnt){ balance=balance+amnt; balance=balance*pow((1+4.5/100), 3); System.out.printf("Account balance updated to Rs. %.2f, adding interest.\n"); } } class CurAccount extends Account { static final char type='c'; CurAccount(String name, String acct, double initBal){ super(name, acct, initBal, type); } public void withdraw()throws IOException { System.out.println("Select withdrawal mode: C>heque or W>ithdrawal slip.");
100
System.out.print("Or, press any key to abort withdrawal. "); char ch; switch(ch=inStream.readLine().charAt(0)){ case 'c': case 'C':System.out.print("Enter cheque number: "); inStream.readLine(); break; case 'w': case 'W':System.out.print("Enter withdrawal slip number: "); inStream.readLine(); break; default: System.out.println("Withdrawal process aborted."); } System.out.print("Enter the amount to be withdrawn: Rs."); float amnt=Float.valueOf(inStream.readLine()).floatValue(); if(amnt>balance) System.out.println("Withdrawal request denied. Account balance insufficient."); else{ if(balance-amnt<MIN_C){ System.out.println("Remaining balance will be less than Rs."+MIN_C+", the minimum
balance. "); System.out.println("Service charge of Rs."+SERVIC+" will be deducted from account
balance. "); System.out.print("Continue withdrawing? (Y/N) ");
switch(ch=inStream.readLine().charAt(0)){ case 'y': case 'Y':balance=balance-(amnt+SERVIC); System.out.println("Rs."+amnt+" withdrawn successfully."); break; default: System.out.println("Withdrawal process aborted."); } } else{ balance=balance-amnt; System.out.println("Rs."+amnt+" withdrawn successfully."); } showBal(); }
} public void deposit(double amnt){ balance=balance+amnt; System.out.printf("Account balance updated to Rs. %.2f\n",balance); } } public class BankService{ public static void main(String[] argArray) throws IOException{ BufferedReader inStream=new BufferedReader(new InputStreamReader(System.in)); Account acc[ ]=new Account[25];
101
int i=0; int j=0; char x=' '; String name, acct; double amount; System.out.println("WELCOME TO THE XYZ BANK"); do{ System.out.println("Enter your choice:"); System.out.println("O>pen a new account."); System.out.println("L>og into an existing account."); System.out.print("E>xit without doing anything. "); switch(x=inStream.readLine().charAt(0)){ case 'o': case 'O':System.out.println("Select account type: S>avings or C>urrent.”);
System.out.print(“Or, enter anything to return to main menu. "); switch(x=inStream.readLine().charAt(0)){ case 's': case 'S':System.out.println("At least Rs.200 should be deposited initially to
open a new savings account."); System.out.print("Proceed? (Y/N) ");
x=inStream.readLine().charAt(0); if(x=='n'||x=='N') break; System.out.println("Please enter the following vital information."); System.out.print("Enter the Customer's name: "); name=inStream.readLine();
System.out.print("Enter the Account number: "); acct=inStream.readLine(); System.out.print("Enter the initialising amount: Rs."); acc[i++]=new SavAccount(name, acct, Account.MIN_S); System.out.println("Savings account created successfully."); break; case 'c': case 'C':System.out.println("At least Rs.450 should be deposited initially to
open a new current account."); System.out.print("Proceed? (Y/N) ");
x=inStream.readLine().charAt(0); if(x=='n'||x=='N') break; System.out.println("Please enter the following vital information."); System.out.print("Enter the Customer's name: "); name=inStream.readLine(); System.out.print("Enter the Account number: "); acct=inStream.readLine(); System.out.print("Enter the initialising amount: Rs."); initBal=Float.parseFloat(inStream.readLine()); acc[i++]=new CurAccount(name, acct, Account.MIN_C); System.out.println("Current account created successfully."); break; default: System.out.println("Main menu:"); } break;
102
case 'l': case 'L': if(i==0){ System.out.println("No accounts created till now."); break; }
System.out.print("Enter the account number to log into: "); acct=inStream.readLine();
for(j=0;j<i && acc[j].matchAcctNo(acct)==false;j++); if(j<=i) do{ System.out.println("Enter your choice: "); System.out.println("V>iew the account status."); System.out.println("W>ithdraw from the account."); System.out.println("D>eposit into the account."); System.out.print("Or, enter anything to return to main menu. "); x=inStream.readLine().charAt(0); switch(x){ case 'v': case 'V':acc[j].showStatus(); break; case 'w': case 'W':acc[j].withdraw(); break; case 'd': case 'D':System.out.print("Enter the amount to be deposited: Rs."); amount=Float.parseFloat(inStream.readLine()); acc[j].deposit(amount); break; default: x='X'; System.out.println("Main menu:");
} }while(x!='X'); else System.out.println("The searched account does not exists."); break; default: System.out.println("Thanks for running the program."); System.exit(0); }
} while (true); //an infinite do-while loop } }
103
OUTPUT: WELCOME TO THE XYZ BANK Enter your choice: O>pen a new account. L>og into an existing account. E>xit without doing anything. O Select account type: S>avings or C>urrent. Or, enter anything to return to main menu. C At least Rs.450 should be deposited initially to open a new current account. Proceed? (Y/N) y Please enter the following vital information. Enter the Customer's name: Rishi Roy Enter the Account number: 101c Current account created successfully. Enter your choice: O>pen a new account. L>og into an existing account. E>xit without doing anything. o Select account type: S>avings or C>urrent. Or, enter anything to return to main menu. s At least Rs.200 should be deposited initially to open a new savings account. Proceed? (Y/N) y Please enter the following vital information. Enter the Customer's name: Mahesh Pandit Enter the Account number: 103s Account balance updated to Rs. 228.23, adding interest. Savings account created successfully. Enter your choice: O>pen a new account. L>og into an existing account. E>xit without doing anything. o Select account type: S>avings or C>urrent. Or, enter anything to return to main menu. c At least Rs.450 should be deposited initially to open a new current account. Proceed? (Y/N) n Enter your choice: O>pen a new account. L>og into an existing account. E>xit without doing anything. L Enter the account number to log into: 103s Enter your choice: V>iew the account status. W>ithdraw from the account. D>eposit into the account. Or, enter anything to return to main menu. v Account number: 103s Account holder: Mahesh Pandit
104
Current balance: Rs.228.23 Enter your choice: V>iew the account status. W>ithdraw from the account. D>eposit into the account. Or, enter anything to return to main menu. D Enter the amount to be deposited: Rs.100.60 Account balance updated to Rs. 375.25, adding interest. Enter your choice: V>iew the account status. W>ithdraw from the account. D>eposit into the account. Or, enter anything to return to main menu. b Main menu: Enter your choice: O>pen a new account. L>og into an existing account. E>xit without doing anything. o Select account type: S>avings or C>urrent. Or, enter anything to return to main menu. C At least Rs.450 should be deposited initially to open a new current account. Proceed? (Y/N) y Please enter the following vital information Enter the Customer’s name: Sailesh Tyaagi Enter the Account number: 102c Current account created successfully. Enter your choice: O>pen a new account. L>og into an existing account. E>xit without doing anything. L Enter the account number to log into: 101c Enter your choice: V>iew the account status. W>ithdraw from the account. D>eposit into the account. Or, enter anything to return to main menu. v Account number: 101c Account holder: Rishi Boy Current balance: Rs.450.0 Enter your choice: V>iew the account status. W>ithdraw from the account. D>eposit into the account. Or, enter anything to return to main menu. d Enter the amount to be deposited: Rs.10.25 Account balance updated to Rs. 460.25 Enter your choice: V>iew the account status. W>ithdraw from the account.
105
D>eposit into the account. Or, enter anything to return to main menu. w Select withdrawal mode: C>heque or W>ithdrawal slip. Or press any key to abort withdrawal. C Enter cheque number: 793v26y Enter the amount to be withdrawn: Rs. 120 .85 Remaining balance will be less than Rs.450.0, the minimum balance. Service charge of Rs.15.0 will be deducted from account balance. Continue withdrawing? (Y/N) y Rs.120.85 withdrawn successfully. Current balance: Rs.324.39 Enter your choice: V>iew the account status. W>ithdraw from the account. D>eposit into the account. Or, enter anything to return to main menu. n Main menu: Enter your choice: O>pen a new account. L>og into an existing account. E>xit without doing anything. L Enter the account number to log into: 103s Enter your choice: V>iew the account status. W>ithdraw from the account. D>eposit into the account. Or, enter anything to return to main menu. w Enter withdrawal slip number: p986y765kj Enter the amount to be withdrawn: Rs. 55.65 Rs.55.65 withdrawn successfully. Current balance: Rs. 319.60 Enter your choice: V>iew the account status. W>ithdraw from the account. D>eposit into the account. Or, enter anything to return to main menu. z Main menu: Enter your choice: O>pen a new account. L>og into an existing account. E>xit without doing anything. E Thanks for running the program.
106
Object Oriented Programming (Java) Practical Assignment - 10
Write a Java program to implement the use of overloading and overriding methods.
107
CODING: //Java assignment module 10 import java.io.*; import java.lang.Math; class BasicPolygon{ double dim1; double dim2; BasicPolygon(double a, double b){ dim1=a; dim2=b; } void areaOfShape(){ System.out.println("Area of BasicShape is undefined."); } } class Triangle extends BasicPolygon{ Triangle(double a, double b){ super(a,b); } void areaOfShape(){ double area=dim1*dim2/2; System.out.println("Area of triangle is "+area+" sq. units"); } } class Quadrilateral extends BasicPolygon{ Quadrilateral(double a, double b){ super(a,b); } void areaOfShape(){ double area=dim1*dim2; System.out.println("Area of quadrilateral (rectangle) is "+area+" sq. units"); } void areaOfShape(double dim){ double area=dim*dim; System.out.println("Area of quadrilateral (square) is "+area+" sq. units"); } } public class OverDemo{ public static void main(String[ ] argArray){ BasicPolygon bp=new BasicPolygon(10,10); Triangle tri=new Triangle(10,8); Quadrilateral quad=new Quadrilateral(9,5); bp.areaOfShape(); tri.areaOfShape(); quad.areaOfShape(); quad.areaOfShape(15); } }
OUTPUT: Area of BasicShape is undefined. Area of triangle is 40.0 sq. units Area of quadrilateral (rectangle) is 45.0 sq. units Area of quadrilateral (square) is 225.0 sq. units
108
Object Oriented Programming (Java) Practical Assignment - 11
Give an example where interface can be used to support multiple inheritances.
Develop a standalone Java program for the example.
109
CODING: //Java assignment module 11 import java.io.*; class Complex implements AddComplex, SubComplex, MulComplex{ double real; double imag; Complex (double r, double i){ real=r; imag=i; } Complex(){ real=0; imag=0; } public String toString(){ if(imag<0) return(real+""+imag+"i"); if(imag==0) return(real+""); if(real==0) return(imag+"i"); return(real+"+"+imag+"i"); } public Complex add(Complex a, Complex b) { return(new Complex(a.real+b.real, a.imag+b.imag)); } public Complex sub(Complex a, Complex b) { return(new Complex(a.real-b.real, a.imag-b.imag)); } public Complex mul(Complex a, Complex b) { return(new Complex((a.real*b.real)-(a.imag*b.imag), (a.real*b.imag)+(a.imag*b.real))); } } interface AddComplex{ public Complex add(Complex a, Complex b); } interface SubComplex{ public Complex sub(Complex a, Complex b); } interface MulComplex{ public Complex mul(Complex a, Complex b); } public class ComplexOperations{ public static void main(String[] argArray) throws IOException{ BufferedReader inStream=new BufferedReader(new InputStreamReader(System.in)); double real=0; double imag=0;
110
System.out.println("Demonstration of multiple inheritance in Java."); System.out.println("This program outputs the sum, difference and product of two complex
numbers."); System.out.println("Enter two complex numbers for the program to continue..."); System.out.print("Real part of first complex number: "); try{real=Float.parseFloat(inStream.readLine());} catch(NumberFormatException numE) {System.out.println("Inavlid number input.");} System.out.print("Imaginary part of first complex number: "); try{imag=Float.parseFloat(inStream.readLine());} catch(NumberFormatException numE) {System.out.println("Inavlid number input.");} Complex com1=new Complex(real,imag); System.out.print("Real part of second complex number: "); try{real=Float.parseFloat(inStream.readLine());} catch(NumberFormatException numE) {System.out.println("Inavlid number input.");} System.out.print("Imaginary part of second complex number: "); try{imag=Float.parseFloat(inStream.readLine());} catch(NumberFormatException numE) {System.out.println("Inavlid number input.");} Complex com2=new Complex(real,imag); System.out.println("Outputting result."); Complex com3=new Complex(); System.out.println("Sum: "+com3.add(com1, com2)); System.out.println("Difference (first minus second): "+com3.sub(com1, com2)); System.out.println("Product: "+com3.mul(com1, com2)); System.out.println("Thanks for running the program."); } }
OUTPUT: Demonstration of multiple inheritance in Java. This program outputs the sum, difference and product of two complex numbers. Enter two complex numbers for the program to continue... Real part of first complex number: 7 Imaginary part of first complex number: 12 Real part of second complex number: 9 Imaginary part of second complex number: 5 Outputting result. Sum: 16.0+17.0i Difference (first minus second): -2.0+7.0i Product: 3.0+143.0i Thanks for running the program.
111
Object Oriented Programming (Java) Practical Assignment - 12
Design a package to contain the class student and another package to contain the
class sports. Write a Java program to import these two packages into class test
and class result.
112
CODING: //File Sports.java defined inside subdirectory "pax" package pax; public class Sports{ public float score; public Sports(float score){ this.score=score; } public void showScore(){ System.out.println("Score in sports: "+score); } public String toString(){ return(score+""); } } //File Student.java defined inside subdirectory "packs" under "pax" package pax.packs; public class Student{ String roll; String name; int age; public Student(String roll, String name, int age){ this.roll=new String(roll); this.name=new String(name); this.age=age; } public void showProfile(){ System.out.println("Roll number: "+roll); System.out.println("Name: "+name); System.out.println("Age: "+age); } } //Java assignment module 12 (file “ReportCard.java”) import java.io.*; class Test extends pax.packs.Student{ int paper1, paper2; public Test(String roll, String name, int age){ super(roll, name, age); paper1=0; paper2=0; } public void getMarks() throws IOException{ BufferedReader inStream=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter marks in first paper: "); paper1=Integer.parseInt(inStream.readLine());
113
System.out.print("Enter marks in second paper: "); paper2=Integer.parseInt(inStream.readLine()); } public void showMarks(){ showProfile(); System.out.println("Marks in paper1: "+paper1); System.out.println("Marks in paper2: "+paper2); } } class Result extends pax.Sports{ Test report; float total; public Result(String roll, String name, int age, float score){ super(score); report= new Test(roll, name, age); total=0; } public void getReport(){ try{ report.getMarks(); } catch(IOException iox){ System.out.println("Error reading input from console: "+iox); } total=report.paper1+report.paper2+score; } public void showResult(){ report.showMarks(); showScore(); System.out.println("Total marks for grading: "+total); } } class ReportCard{ public static void main(String[] argArray) throws IOException{ BufferedReader inStream=new BufferedReader(new InputStreamReader(System.in)); String str1, str2; int i=0; System.out.println("This java program is for creating a student's report card."); System.out.print("Enter the student's roll number: "); str1=new String(inStream.readLine()); System.out.print("Enter student's name: "); str2=new String(inStream.readLine()); System.out.print("Enter student's age: "); i=Integer.parseInt(inStream.readLine()); System.out.print("Enter student's score in sports: "); Result res=new Result(str1, str2, i, Float.parseFloat(inStream.readLine())); res.getReport(); res.showResult(); System.out.println("Thanks for running the program."); }
114
OUTPUT: This java program is for creating a student's report card.
Enter the student's roll number: 37
Enter student's name: Abc Xyz
Enter student's age: 21
Enter student's score in sports: 79
Enter marks in first paper: 53
Enter marks in second paper: 67
Roll number: 37
Name: Abc Xyz
Age: 21
Marks in paper1: 53
Marks in paper2: 67
Score in sports: 79.0
Total marks for grading: 199.0
Thanks for running the program.
115
Object Oriented Programming (Java) Practical Assignment - 13
Write a Java program to implement various thread methods i.e. yield( ), stop( ),
run( ), start( ) and sleep( ) methods.
116
CODING: //Java assignment module 13 import static java.lang.Thread.*; import static java.lang.Thread.State.*; import java.io.*; class FactThread extends Thread{ int times; public FactThread(int val){ times=val; this.setName("Factorial thread"); } int fact(int arg){ if(arg>0) return(arg*fact(arg-1)); return 1; } public void run(){ System.out.println("Child thread: "+this); int num=0; while(num<=times){ if(num==7) try{ sleep(2000); System.out.println(this.getName()+" put to sleep."); } catch(InterruptedException iex){ System.out.println("Thread "+this.getName()+" interrupted: "+iex); } if(num==3){ System.out.println("Yielding from "+this.getName()); yield(); } if(num==9){ System.out.println("Stopped "+this.getName()); stop(); } System.out.println(num+" ! ="+fact(num++)); } } } class SquareThread extends Thread{ int times; public SquareThread(int val){ times=val; this.setName("Square thread"); } public void run(){
117
System.out.println("Child thread: "+this); int num=0; while(num<=times){ if(num==2) try{ sleep(2000); System.out.println(this.getName()+" put to sleep."); } catch(InterruptedException iex){ System.out.println("Thread "+this.getName()+" interrupted: "+iex); } if(num==6){ System.out.println("Yielding from "+this.getName()); yield(); } if(num==14){ System.out.println("Stopped "+this.getName()); stop(); } System.out.println(num+" squared is "+(num*num++)); } } } public class ThreadMethodsDemo{ public static void main(String argArray[]) throws IOException{ BufferedReader inStream=new BufferedReader(new InputStreamReader(System.in)); System.out.println("This program is to demonstrate multiple threading in Java."); System.out.print("Enter an integer value, preferably more than 10 : "); int value=Integer.parseInt(inStream.readLine()); FactThread thread_one=new FactThread(value); SquareThread thread_two=new SquareThread(value); thread_one.start(); thread_two.start(); while(value>0){ System.out.println("From main thread: "+ value--); if(thread_one.getState()==TERMINATED && thread_two.getState()==TERMINATED){ System.out.println("All threads exited."); System.exit(0); } else if(value==0) System.out.println("Main thread exited."); } } }
118
OUTPUT: This program is to demonstrate multiple threading in Java. Enter an integer value, preferably more than 10 : 13 Child thread: Thread[Square thread,5,main] 0 squared is 0 1 squared is 1 From main thread: 13 Child thread: Thread[Factorial thread,5,main] 0 ! =1 1 ! =1 2 ! =2 Yielding from Factorial thread 3 ! =6 4 ! =24 5 ! =120 6 ! =720 From main thread: 12 From main thread: 11 From main thread: 10 From main thread: 9 From main thread: 8 From main thread: 7 From main thread: 6 From main thread: 5 From main thread: 4 From main thread: 3 From main thread: 2 From main thread: 1 Main thread exited. Square thread put to sleep. 2 squared is 4 3 squared is 9 4 squared is 16 5 squared is 25 Yielding from Square thread 6 squared is 36 7 squared is 49 8 squared is 64 9 squared is 81 10 squared is 100 11 squared is 121 12 squared is 144 13 squared is 169 Factorial thread put to sleep. 7 ! =5040 8 ! =40320 Stopped Factorial thread
119
Object Oriented Programming (Java) Practical Assignment - 14
Write a Java program to implement the concept of Runnable interface.
120
CODING: //Java assignment module 14 import java.lang.Runnable; import java.lang.Thread; import java.io.*; class ThreadOne implements Runnable{ int times; public ThreadOne(int val){ Thread aThread=new Thread(this, "ThreadOne"); times=val; System.out.println("Child thread: "+aThread); aThread.start(); } public void run(){ while(times>=0) System.out.println("From ThreadOne: "+times--); } } public class ThreadDemo{ public static void main(String argArray[ ]) throws IOException{ BufferedReader inStream=new BufferedReader(new InputStreamReader(System.in)); System.out.println("This program is to demonstrate the implementation of Runnble interface."); System.out.print("Enter an integer value, preferably less than 10 : "); int value=Integer.parseInt(inStream.readLine()); int i=0; new ThreadOne(value); while(i<=value) System.out.println("From main thread: "+i++); } }
OUTPUT: This program is to demonstrate the implementation of Runnble interface. Enter an integer value, preferably less than 10 : 7 Child thread: Thread[ThreadOne,5,main] From main thread: 0 From ThreadOne: 7 From main thread: 1 From ThreadOne: 6 From main thread: 2 From ThreadOne: 5 From main thread: 3 From ThreadOne: 4 From main thread: 4 From ThreadOne: 3 From ThreadOne: 2 From ThreadOne: 1 From ThreadOne: 0 From main thread: 5 From main thread: 6 From main thread: 7
121
Object Oriented Programming (Java) Practical Assignment - 15
Define an Exception called “NoMatchException” that is thrown when a string is
not equal to “Assam”. Write a program that uses this exception.
122
CODING: //Java assignment module 15 import java.io.*; class NoMatchException extends Exception{ private String paramString; NoMatchException(String str){ paramString=new String(str); } public String toString(){ return("NoMatchException: Parameter String=\""+paramString+"\""); } } public class CustomException{ static String aString; static void matchString(String param) throws NoMatchException{ System.out.println("Matching string..."); if(param.equals("Assam")==false) throw new NoMatchException(param); System.out.println("String matched."); } public static void main(String argArray[ ]){ BufferedReader inStream=new BufferedReader(new InputStreamReader(System.in)); System.out.println("This program matches your input string to the string \"Assam\"."); System.out.print("Enter a string: "); try{ aString=new String(inStream.readLine()); } catch(IOException ioe){ System.out.println("Error reading string from console."); System.exit(1); } try{ matchString(aString); } catch(NoMatchException nm){ System.out.println("Exception caught: "+nm); } System.out.println("Thanks for running the program."); } }
OUTPUT: C:\Java files>java CustomException This program matches your input string to the string "Assam". Enter a string: assam Matching string... Exception caught: NoMatchException: Parameter String="assam" Thanks for running the program.
123
Object Oriented Programming (Java) Practical Assignment - 16
Write a Java program to append names to a file already containing a few names.
124
CODING:
//Java assignment module 16
import java.io.*;
class AppendToFile{
public static void main(String[ ] argArray) throws IOException{
BufferedReader inStream= new BufferedReader(new InputStreamReader(System.in));
System.out.println("This Java program appends names to a file.");
System.out.print("Enter a file name : ");
String str= new String(inStream.readLine());
String str1;
FileWriter outStream= new FileWriter(str.trim(), true);
System.out.println("File "+str+" opened in append mode.");
do{
System.out.print("Enter a name : ");
str1=inStream.readLine();
outStream.write("\n"+str1);
System.out.println("Name written to file.");
System.out.print("Append more names to the file? (Y/N) ");
}while(Character.toUpperCase(inStream.readLine().charAt(0))!='N');
outStream.close();
inStream=new BufferedReader(new FileReader(str.trim()));
System.out.println("The contents of the file are:");
while((str=inStream.readLine())!=null)
System.out.println(str);
inStream.close();
System.out.println("\t\tThanks for running the program.");
}
}
125
OUTPUT:
This Java program appends names to a file.
Enter a file name : NameList.txt
File NameList.txt opened in append mode.
Enter a name : Rajan
Name written to file.
Append more names to the file? (Y/N) y
Enter a name : Joy
Name written to file.
Append more names to the file? (Y/N) y
Enter a name : Kumar
Name written to file.
Append more names to the file? (Y/N) n
The contents of the file are:
Ajay
Rahul
Gautam
Shakti
Mridul
Rajan
Joy
Kumar
Thanks for running the program.
126
Object Oriented Programming (Java) Practical Assignment - 17
Write a Java program to demonstrate concatenating and buffering of files.
127
CODING:
//Java assignment module 17 import java.io.*; class BufferFiles{ public static void main(String[ ] argArray) throws IOException{ System.out.println("This Java program demonstrates concatenating and buffering of
files."); int c=0; FileInputStream streamOne=null; FileInputStream streamTwo=null; BufferedReader inStream= new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter two valid file names:"); String str1=new String(inStream.readLine().trim()); String str2=new String(inStream.readLine().trim()); try{ streamOne=new FileInputStream(str1); streamTwo=new FileInputStream(str2); } catch(Exception ex){ System.out.println("Exception occured in file operation: "+ex); } SequenceInputStream oneTwo= new SequenceInputStream(streamOne, streamTwo); BufferedInputStream buffIn= new BufferedInputStream(oneTwo); BufferedOutputStream buffOut= new BufferedOutputStream(System.out); while((c=buffIn.read())!=-1) buffOut.write(c); buffOut.flush(); buffIn.close(); streamOne.close(); streamTwo.close(); System.out.println("\n\n\t\t End of two files."); } }
OUTPUT:
This Java program demonstrates concatenating and buffering of files. Enter two valid file names: MyFile.txt AnotherFile.txt This program is for concatenating and buffering two text files. Names of two already existing files should be given as input. The program concatenates those two files and displays the result. The result is displayed on the visual display unit. End of two files.
128
Object Oriented Programming (Java) Practical Assignment - 18
Write a Java program to create a sequential file that could store details about
five products. Details include product code, cost and number of items available
and are provided through the keyboard.
129
CODING:
//Java assignment module 18
import java.io.*;
class SeqFile{
public static void main(String[ ] argArray) throws IOException{
BufferedReader inStream= new BufferedReader(new InputStreamReader(System.in));
System.out.println("This Java program creates a sequential file to store details of
products.");
System.out.print("Enter the filename to create: ");
String str= new String(inStream.readLine());
String str1; int i=0;
FileWriter outStream= new FileWriter(str.trim());
do{
System.out.print("Enter a product code : ");
str1=inStream.readLine();
outStream.write(str1+"\n");
System.out.print("Enter cost of the product : Rs. ");
str1=inStream.readLine();
outStream.write(str1+"\n");
System.out.print("Enter the number of items available : ");
str1=inStream.readLine();
outStream.write(str1+"\n");
System.out.println("Information written to file.");
System.out.print("Write more product information to the file? (Y/N) ");
}while(Character.toUpperCase(inStream.readLine().charAt(0))!='N');
outStream.close();
inStream=new BufferedReader(new FileReader(str.trim()));
System.out.println("The data in the file are:");
System.out.println("Code\tPrice\t\tNos.");
while((str=inStream.readLine())!=null){
System.out.print(str+" \t");i++;
if(i%3==0) System.out.println("");
}
inStream.close();
System.out.println("\tThanks for running the program.");
}
}
130
OUTPUT:
This Java program creates a sequential file to store details of products.
Enter the filename to create: AseqFile.txt
Enter product code : A18
Enter cost of the product : Rs. 345.98
Enter the number of items available : 15
Information written to file.
Write more product information to the file? (Y/N) y
Enter product code : XK98
Enter cost of the product : Rs. 67.88
Enter the number of items available : 463
Information written to file.
Write more product information to the file? (Y/N) y
Enter product code : V765
Enter cost of the product : Rs. 90.60
Enter the number of items available : 43
Information written to file.
Write more product information to the file? (Y/N) n
The data in the file are:
Code Price Nos.
A18 345.98 15
XK98 67.88 463
V765 90.60 43
Thanks for running the program.
131
Object Oriented Programming (Java) Practical Assignment - 19
Rewrite the previous program (i.e., Practical Assignment 18) using random access
file so that we can add more products to the file, if necessary.
132
CODING:
//Java assignment module 19
import java.io.*;
class RandomFile{
public static void main(String[ ] argArray) throws IOException{
RandomAccessFile fileStream=null;
BufferedReader inStream= new BufferedReader(new InputStreamReader(System.in));
String str;int i=0;
System.out.println("This Java program creates a random access file to store details of
products.");
System.out.print("Enter the filename : ");
str=new String(inStream.readLine().trim());
fileStream= new RandomAccessFile(str , "rw");
System.out.print("Append a record to the file? (Y/N) ");
if(Character.toUpperCase(inStream.readLine().charAt(0))!='N')
{
fileStream.seek(fileStream.length());
do{
System.out.print("Enter product code : ");
fileStream.writeBytes(inStream.readLine()+"\n");
System.out.print("Enter cost of the product : ");
fileStream.writeBytes(inStream.readLine()+"\n");
System.out.print("Enter the number of items available : ");
fileStream.writeBytes(inStream.readLine()+"\n");
System.out.println("Information written to file.");
System.out.print("Write more product information to the file? (Y/N) ");
}while(Character.toUpperCase(inStream.readLine().charAt(0))!='N');
}
fileStream.seek(0);
System.out.println("Contents of the updated file: ");
System.out.println("Code\tPrice\tNos.");
while((str=fileStream.readLine())!=null){
System.out.print(str+" \t");i++;
if(i%3==0)
System.out.println("");
}
System.out.println("\tThanks for running the program.");
}
}
133
OUTPUT:
This Java program creates a random access file to store details of products.
Enter the filename : apjfile.txt
Append a record to the file? (Y/N) y
Enter product code : ds8
Enter cost of the product : 45.36
Enter the number of items available : 85
Information written to file.
Write more product information to the file? (Y/N) n
Contents of the updated file:
Code Price Nos.
p98 14.70 70
i65 25.80 80
y32 36.90 90
nm7 45.60 60
vb6 23.00 45
as7 56.90 14
ds8 45.36 85
Thanks for running the program.
134
Object Oriented Programming (Java) Practical Assignment - 20
Write a Java program to create a TextField that allows only numeric values and
in specified length.
135
CODING:
//Java assignment module 20 import java.awt.*; import java.awt.event.*; import static java.awt.event.KeyEvent.*; import java.applet.*; public class NumField extends Applet implements KeyListener{ TextField t; Label lb; public void keyPressed(KeyEvent ev){ int code=ev.getKeyCode(); String str=new String(ev.getKeyText(code));
if(ev.isActionKey()==true||code==VK_BACK_SPACE||code==VK_ENTER||code==VK_DELETE) return; if(Character.isDigit(ev.getKeyChar())==false||t.getText().length()==5) t.setEditable(false); } public void keyReleased(KeyEvent ev){ t.setEditable(true); } public void keyTyped(KeyEvent ev){} public void init(){ t=new TextField("",5); lb=new Label("This text field takes only numeric values upto 5 digits."); add(lb); add(t); t.addKeyListener(this); } } /*<applet code="NumField.class" height=300 width=350></applet>*/
OUTPUT:
136
Object Oriented Programming (Java) Practical Assignment - 21
Develop an Applet that receives three numeric values as input from the user and
then displays the largest of the three on the screen. Write a HTML page and test
the applet.
137
CODING:
//Java assignment module 21 import java.awt.*; import java.applet.*; import java.awt.event.*; public class GreatestNum extends Applet implements ActionListener{ TextField txt[]; Label lbl[]; Button btn; int i=0; public void init(){ txt=new TextField[3]; lbl=new Label[5]; for(i=0;i<3;i++){ txt[i]=new TextField("0",5); lbl[i]=new Label(); } lbl[i]=new Label(); btn=new Button("Find greatest integer"); lbl[0].setText("Finding the greatest of three integers."); lbl[1].setText("First number"); lbl[2].setText("Second number"); lbl[3].setText("Third number"); add(lbl[0]); for(i=0;i<3;i++){ add(lbl[i+1]); add(txt[i]); } add(btn); btn.addActionListener(this); } public void paint(Graphics g){ if(i==0) g.drawString("The greatest number is "+this.greatest(),30,170); i=0; } int greatest(){ int a[]=new int[3]; int greatest; try{ for(int x=0;x<3;x++) a[x]=Integer.parseInt(txt[x].getText()); } catch(Exception e){} if(a[0]>a[1])
greatest=a[0]; else greatest=a[1];
138
if(a[2]>greatest) greatest=a[2]; return greatest; } public void actionPerformed(ActionEvent ev){ repaint(); } } /*<applet code="GreatestNum.class" width=233 height=189></applet>*/ Coding in the HTML page “Java Interface.html” <html> <head> <title> Java Interface </title> </head> <body> <applet code="GreatestNum.class" width=233 height=189> Java applets not supported </applet> </body> </html>
OUTPUT:
139
Object Oriented Programming (Java) Practical Assignment - 22
Write a Java program to create a Frame and a CheckBox group with five
CheckBoxes, with label as Red, Green, Blue, Yellow and White. At runtime change
the background colour of the form with appropriate selection of the checkbox.
140
CODING:
//Java assignment module 22 import java.applet.*; import java.awt.*; import java.awt.event.*; public class ChangeColor extends Frame implements ItemListener{ CheckboxGroup cbg; Checkbox cbx[]; public ChangeColor(){ super("Color selector"); setLayout(new FlowLayout(FlowLayout.CENTER)); cbg = new CheckboxGroup(); cbx=new Checkbox[5]; cbx[0]=new Checkbox("Red", cbg, false); cbx[1]=new Checkbox("Green", cbg, false); cbx[2]=new Checkbox("Blue", cbg, false); cbx[3]=new Checkbox("Yellow", cbg, false); cbx[4]=new Checkbox("White", cbg, true); for(int i=0;i<5;i++){ add(cbx[i]); cbx[i].addItemListener(this); } addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ System.exit(0); } }); } public void itemStateChanged(ItemEvent ev){ if(cbg.getSelectedCheckbox().getLabel()=="Red") setBackground(Color.RED); if(cbg.getSelectedCheckbox().getLabel()=="Green") setBackground(Color.GREEN); if(cbg.getSelectedCheckbox().getLabel()=="Blue") setBackground(Color.BLUE); if(cbg.getSelectedCheckbox().getLabel()=="Yellow") setBackground(Color.YELLOW); if(cbg.getSelectedCheckbox().getLabel()=="White") setBackground(Color.WHITE); } public static void main(String[ ] argArray){ Frame app=new ChangeColor(); app.setSize(250,200); app.setVisible(true); } }
141
OUTPUT:
142
Object Oriented Programming (Java) Practical Assignment - 23
Write a Java program to create a Frame with three Scrolls, change the background
colour of the Frame using RGB function with values of scrolls.
143
CODING:
//Java assignment module 23 import java.applet.*; import java.awt.*; import java.awt.event.*; public class RgbFrame extends Frame implements AdjustmentListener{ Scrollbar redScroll, greenScroll, blueScroll; Label rLb, gLb, bLb; public RgbFrame(){ super("Color Mixer"); setLayout(new FlowLayout(FlowLayout.CENTER)); redScroll=new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,255); greenScroll=new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,255); blueScroll=new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,255); rLb=new Label(" Red "); gLb=new Label(" Green "); bLb=new Label(" Blue "); add(redScroll); add(greenScroll); add(blueScroll); add(rLb); add(gLb); add(bLb); redScroll.addAdjustmentListener(this); blueScroll.addAdjustmentListener(this); greenScroll.addAdjustmentListener(this); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ System.exit(0); } }); } public void adjustmentValueChanged(AdjustmentEvent ae){ setBackground(new Color(redScroll.getValue(), greenScroll.getValue(), blueScroll.getValue())); } public static void main(String[] argArray){ RgbFrame app=new RgbFrame(); app.setSize(200,150); app.setVisible(true); } } OUTPUT:
144
Object Oriented Programming (Java) Practical Assignment - 24
Write a Java program to create a Frame, Choice and Label. Add five items in the
choice. At runtime display the selected items of choice in the label.
145
CODING:
//Java assignment module 24 import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class ChoiceFrame extends Frame implements ItemListener{
Label lb;
Choice Chooser;
public ChoiceFrame(){
super("Option selector");
setLayout(new FlowLayout(FlowLayout.CENTER, 0, 35));
Chooser = new Choice();
Chooser.add("One");
Chooser.add("Two");
Chooser.add("Three");
Chooser.add("Four");
Chooser.add("Five");
lb=new Label("Selected option will be displayed here", Label.CENTER);
add(Chooser);
add(lb);
Chooser.addItemListener(this);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
public void itemStateChanged(ItemEvent ite){
lb.setText(Chooser.getSelectedItem());
}
public static void main(String[ ] argArray){
Frame app=new ChoiceFrame();
app.setSize(250,200); app.setVisible(true);
}
}
146
OUTPUT:
PPRRAACCTTIICCAALL AASSSSIIGGNNMMEENNTTSS
DDAATTAABBAASSEE MMAANNAAGGEEMMEENNTT SSYYSSTTEEMM
147
TTOOOOLLSS,, PPLLAATTFFOORRMM,, LLAANNGGUUAAGGEE AANNDD HHAARRDDWWAARREE UUSSEEDD
Machine type: IBM Think Centre
CPU type: Pentium 4
Co-processor: Installed
CPU clock: 2.8 GHz
RAM: 256 MB
Display type: VGA mono and upward compatibility
Hard disk: 40 GB
Floppy disk: 1.44 MB
Operating System: Microsoft Windows XP Professional
Query Language: SQL
RDBMS Package: Oracle 9i
148
Assignment # 1
Create table category_header with the following structure:
Cat_code number (5), cat_desc varchar2 (20)
Query: SQL> create table category_header(cat_code number(5),cat_desc varchar2(20));
Result: SQL> desc category_header;
Name Null? Type
----------------------------------------- -------- ----------------------------
CAT_CODE NUMBER(5)
CAT_DESC VARCHAR2(20)
Assignment # 2
Create table route_header for the given column definitions:
Route_id number (5), route_no number (5), cat_code number (5), origin varchar2 (20), Destination
varchar2 (20), destination varchar2 (20), fare number (7, 2), distance number (3), capacity number (3).
Query: SQL> create table route_header (route_id number(5), route_no number(5), cat_code
number(5), origin varchar2(20), destination varchar2(20), frame number(7,2),
distance number(3), capacity number(3));
Table created.
Result: SQL> desc route_header;
Name Null? Type
----------------------------------------- -------- ----------------------------
ROUTE_ID NUMBER(5)
ROUTE_NO NUMBER(5)
CAT_CODE NUMBER(5)
ORIGIN VARCHAR2(20)
DESTINATION VARCHAR2(20)
FRAME NUMBER(7,2)
DISTANCE NUMBER(3)
CAPACITY NUMBER(3)
149
Assignment # 3
Create table place_header whose column definitions are provided in the table below. Place_id number
(5), place_name varchar2 (20), place_address varchar2 (20), bus_station varchar2 (10).
Query: SQL> create table place_header(place_id number(5), place_name varchar2(20),
place_address varchar2(30), bus_station varchar2(10));
Table created.
Result: SQL> desc place_header;
Name Null? Type
----------------------------------------- -------- ----------------------------
PLACE_ID NUMBER(5)
PLACE_NAME VARCHAR2(20)
PLACE_ADDRESS VARCHAR2(30)
BUS_STATION VARCHAR2(10)
Assignment # 4
Create another table fleet_header with the following column description:
Fleet_id number (5), day date, route_id number (5), cat_code number (5)
Query: SQL> create table fleet_header(fleet_id number(5),day date,route_id
number(5),cat_code number(5));
Table created.
Result: SQL> desc fleet_header;
Name Null? Type
----------------------------------------- -------- ----------------------------
FLEET_ID NUMBER(5)
DAY DATE
ROUTE_ID NUMBER(5)
CAT_CODE NUMBER(5)
150
Assignment # 5 Create table ticket_header with the given columns:
Fleet_id number (5), ticket_no number (5), doi date, dot date, time_travel char (8), board_place
varchar2 (20), origin varchar2 (20), destination varchar2 (20), adults number (3), children number (3),
total_fare number (7,2), route_id number (3)
Query: SQL> create table ticket_header(fleet_id number(5), ticket_no number(5), doi date, dot date, time_travel char(8), board_place varchar2(20), origin varchar2(20), destination varchar2(20), adults number(3), children number(3), total_fare number(7,2), route_id number(5)); Table created.
Result: SQL> desc ticket_header; Name Null? Type ----------------------------------------- -------- ---------------------------- FLEET_ID NUMBER(5) TICKET_NO NUMBER(5) DOI DATE DOT DATE TIME_TRAVEL CHAR(8) BOARD_PLACE VARCHAR2(20) ORIGIN VARCHAR2(20) DESTINATION VARCHAR2(20) ADULTS NUMBER(3) CHILDREN NUMBER(3) TOTAL_FARE NUMBER(7,2) ROUTE_ID NUMBER(5)
Assignment # 6 Create table ticket_detail, the structure of which is given in the table below.
Ticket_no number (5), name varchar2 (20), sex char (1), age number (3), fare number (5, 2)
Query: SQL> create table ticket_detail(ticket_no number(5),name varchar2(20),sex char(1),age number(3),fare number(5,2)); Table created.
Result: SQL> desc ticket_detail; Name Null? Type ----------------------------------------- -------- ---------------------------- TICKET_NO NUMBER(5) NAME VARCHAR2(20) SEX CHAR(1) AGE NUMBER(3) FARE NUMBER(5,2)
151
Assignment # 7 Insert into the table category_header the following values:
Cat_code Cat_desc
01 Super deluxe
02 Deluxe
03 Super fast
04 Normal
Query: SQL> insert into category_header values (&CAT_CODE, '&CAT_DESC'); Enter value for cat_code: 01
Enter value for cat_desc: Super deluxe old 1: insert into category_header values (&CAT_CODE, '&CAT_DESC') new 1: insert into category_header values (01, 'Super deluxe')
1 row created.
SQL> / Enter value for cat_code: 02 Enter value for cat_desc: Deluxe
old 1: insert into category_header values (&CAT_CODE, '&CAT_DESC') new 1: insert into category_header values (02, 'Deluxe')
1 row created. SQL> /
Enter value for cat_code: 03 Enter value for cat_desc: Super fast old 1: insert into category_header values (&CAT_CODE, '&CAT_DESC')
new 1: insert into category_header values (03, 'Super fast') 1 row created.
SQL> / Enter value for cat_code: 04
Enter value for cat_desc: Normal old 1: insert into category_header values (&CAT_CODE, '&CAT_DESC') new 1: insert into category_header values (04, 'Normal')
1 row created.
Result: SQL> select * from category_header; CAT_CODE CAT_DESC
---------- -------------------- 1 Super deluxe 2 Deluxe
3 Super fast 4 Normal
152
Assignment # 8
Insert into the table route_header the following values: Route_id Route_no Cat_code Origin Destination Fare Distance Capacity 101 33 01 Madurai Madras 35 250 50 102 25 02 Trichy Madurai 40 159 50 103 15 03 Thanjavur Madurai 59 140 50 104 36 04 Madras Bangalore 79 375 50 105 40 01 Bangalore Madras 80 375 50 106 38 02 Madras Madurai 39 250 50 107 39 03 Hyderabad Madras 50 430 50 108 41 04 Madras Cochin 47 576 50 Query: SQL> insert into route_header values (&ROUTE_ID, &ROUTE_NO, &CAT_CODE, '&ORIGIN',
'&DESTINATION', &FARE, &DISTANCE, &CAPACITY);
Enter value for route_id: 101
Enter value for route_no: 33
Enter value for cat_code: 01
Enter value for origin: Madurai
Enter value for destination: Madras
Enter value for fare: 35
Enter value for distance: 250
Enter value for capacity: 50
old 1: insert into route_header values (&ROUTE_ID, &ROUTE_NO, &CAT_CODE,
'&ORIGIN', '&DESTINATION', &FARE,
new 1: insert into route_header values (101, 33, 01, 'Madurai', 'Madras', 35,
250, 50)
1 row created.
SQL> /
Enter value for route_id: 102
Enter value for route_no: 25
Enter value for cat_code: 02
Enter value for origin: Trichy
Enter value for destination: Madurai
Enter value for fare: 40
Enter value for distance: 159
Enter value for capacity: 50
old 1: insert into route_header values (&ROUTE_ID, &ROUTE_NO, &CAT_CODE,
'&ORIGIN', '&DESTINATION', &FARE,
new 1: insert into route_header values (102, 25, 02, 'Trichy', 'Madurai', 40,
159, 50)
1 row created.
SQL> /
Enter value for route_id: 103
Enter value for route_no: 15
Enter value for cat_code: 03
Enter value for origin: Thanjavur
Enter value for destination: Madurai
Enter value for fare: 59
153
Enter value for distance: 140
Enter value for capacity: 50
old 1: insert into route_header values (&ROUTE_ID, &ROUTE_NO, &CAT_CODE,
'&ORIGIN', '&DESTINATION', &FARE,
new 1: insert into route_header values (103, 15, 03, 'Thanjavur', 'Madurai', 59,
140, 50)
1 row created.
SQL> /
Enter value for route_id: 104
Enter value for route_no: 36
Enter value for cat_code: 04
Enter value for origin: Madras
Enter value for destination: Bangalore
Enter value for fare: 79
Enter value for distance: 375
Enter value for capacity: 50
old 1: insert into route_header values (&ROUTE_ID, &ROUTE_NO, &CAT_CODE,
'&ORIGIN', '&DESTINATION', &FARE,
new 1: insert into route_header values (104, 36, 04, 'Madras', 'Bangalore', 79,
375, 50)
1 row created.
SQL> /
Enter value for route_id: 105
Enter value for route_no: 40
Enter value for cat_code: 01
Enter value for origin: Bangalore
Enter value for destination: Madras
Enter value for fare: 80
Enter value for distance: 375
Enter value for capacity: 50
old 1: insert into route_header values (&ROUTE_ID, &ROUTE_NO, &CAT_CODE,
'&ORIGIN', '&DESTINATION', &FARE,
new 1: insert into route_header values (105, 40, 01, 'Bangalore', 'Madras', 80,
375, 50)
1 row created.
SQL> /
Enter value for route_id: 106
Enter value for route_no: 38
Enter value for cat_code: 02
Enter value for origin: Madras
Enter value for destination: Madurai
Enter value for fare: 39
Enter value for distance: 250
Enter value for capacity: 50
old 1: insert into route_header values (&ROUTE_ID, &ROUTE_NO, &CAT_CODE,
'&ORIGIN', '&DESTINATION', &FARE,
new 1: insert into route_header values (106, 38, 02, 'Madras', 'Madurai', 39,
250, 50)
1 row created.
154
SQL> /
Enter value for route_id: 107
Enter value for route_no: 39
Enter value for cat_code: 03
Enter value for origin: Hyderabad
Enter value for destination: Madras
Enter value for fare: 50
Enter value for distance: 430
Enter value for capacity: 50
old 1: insert into route_header values (&ROUTE_ID, &ROUTE_NO, &CAT_CODE,
'&ORIGIN', '&DESTINATION', &FARE,
new 1: insert into route_header values (107, 39, 03, 'Hyderabad', 'Madras', 50,
430, 50)
1 row created.
SQL> /
Enter value for route_id: 108
Enter value for route_no: 41
Enter value for cat_code: 04
Enter value for origin: Madras
Enter value for destination: Cochin
Enter value for fare: 47
Enter value for distance: 576
Enter value for capacity: 50
old 1: insert into route_header values (&ROUTE_ID, &ROUTE_NO, &CAT_CODE,
'&ORIGIN', '&DESTINATION', &FARE,
new 1: insert into route_header values (108, 41, 04, 'Madras', 'Cochin', 47,
576, 50)
1 row created.
Result: SQL> select * from route_header;
ROUTE_ID ROUTE_NO CAT_CODE ORIGIN DESTINATION FRAME DISTANCE CAPACITY
---------- ---------- ---------- ------------ --------------- ------- ---------- ----------
101 33 1 Madurai Madras 35 250 50
102 25 2 Trichy Madurai 40 159 50
103 15 3 Thanjavur Madurai 59 140 50
104 36 4 Madras Bangalore 79 375 50
105 40 1 Bangalore Madras 80 375 50
106 38 2 Madras Madurai 39 250 50
107 39 3 Hyderabad Madras 50 430 50
108 41 4 Madras Cochin 47 576 50
8 rows selected.
155
Assignment # 9
Insert into the place_header the following values:
Place_id Place_name Place_address Bus_station
01 Madras 10, ptc road Parrys
02 Madurai 21, canalbank road Kknagar
03 Trichy 11, first cross road Bheltown
04 Bangalore 15, first main road Cubbon park
05 Hyderabad 115, lake view road Charminar
06 Thanjavur 12, temple road Railway jn
Query: SQL> insert into place_header values (&PLACE_ID, '&PLACE_NAME', '&PLACE_ADDRESS', '&BUS_STATION'); Enter value for place_id: 01 Enter value for place_name: Madras Enter value for place_address: 10, ptc road Enter value for bus_station: Parrys old 1: insert into place_header values (&PLACE_ID, '&PLACE_NAME', '&PLACE_ADDRESS', '&BUS_STATION') new 1: insert into place_header values (01, 'Madras', '10, ptc road', 'Parrys') 1 row created. SQL> / Enter value for place_id: 02 Enter value for place_name: Madurai Enter value for place_address: 21, canalbank road Enter value for bus_station: Kknagar old 1: insert into place_header values (&PLACE_ID, '&PLACE_NAME', '&PLACE_ADDRESS', '&BUS_STATION') new 1: insert into place_header values (02, 'Madurai', '21, canalbank road', 'Kknagar') 1 row created. SQL> / Enter value for place_id: 03 Enter value for place_name: Trichy Enter value for place_address: 11, first cross road Enter value for bus_station: Bheltown old 1: insert into place_header values (&PLACE_ID, '&PLACE_NAME', '&PLACE_ADDRESS', '&BUS_STATION') new 1: insert into place_header values (03, 'Trichy', '11, first cross road', 'Bheltown') 1 row created.
156
SQL> / Enter value for place_id: 04 Enter value for place_name: Bangalore Enter value for place_address: 15, firstmainroad Enter value for bus_station: Cubbonpark old 1: insert into place_header values (&PLACE_ID, '&PLACE_NAME', '&PLACE_ADDRESS', '&BUS_STATION') new 1: insert into place_header values (04, 'Bangalore', '15, firstmainroad', 'Cubbonpark') 1 row created. SQL> / Enter value for place_id: 05 Enter value for place_name: Hyderabad Enter value for place_address: 115, lakeview road Enter value for bus_station: Charminar old 1: insert into place_header values (&PLACE_ID, '&PLACE_NAME', '&PLACE_ADDRESS', '&BUS_STATION') new 1: insert into place_header values (05, 'Hyderabad', '115, lakeview road', 'Charminar') 1 row created. SQL> / Enter value for place_id: 06 Enter value for place_name: Thanjavur Enter value for place_address: 12, temple road Enter value for bus_station: Railway jn old 1: insert into place_header values (&PLACE_ID, '&PLACE_NAME', '&PLACE_ADDRESS', '&BUS_STATION') new 1: insert into place_header values (06, 'Thanjavur', '12, temple road', 'Railway jn') 1 row created.
Result: SQL> select * from place_header; PLACE_ID PLACE_NAME PLACE_ADDRESS BUS_STATIO ---------- -------------------- ------------------------------ ---------- 1 Madras 10, ptc road Parrys 2 Madurai 21, canalbank road Kknagar 3 Trichy 11, first cross road Bheltown 4 Bangalore 15, firstmainroad Cubbonpark 5 Hyderabad 115, lakeview road Charminar 6 Thanjavur 12, temple road Railway jn 6 rows selected.
157
Assignment # 10
Insert into fleet_header the following values:
Fleet_id Day Route_id Cat_code
01 10-apr-96 101 01
02 10-apr-96 101 01
03 10-apr-96 101 01
04 10-apr-96 102 02
05 10-apr-96 102 03
06 10-apr-96 103 04
Query: SQL> insert into fleet_header values(&FLEET_ID, '&DAY', &ROUTE_ID, &CAT_CODE);
Enter value for fleet_id: 01
Enter value for day: 10-apr-96
Enter value for route_id: 101
Enter value for cat_code: 01
old 1: insert into fleet_header values(&FLEET_ID, '&DAY', &ROUTE_ID, &CAT_CODE)
new 1: insert into fleet_header values(01, '10-apr-96', 101, 01)
1 row created.
SQL> /
Enter value for fleet_id: 02
Enter value for day: 10-apr-96
Enter value for route_id: 101
Enter value for cat_code: 01
old 1: insert into fleet_header values(&FLEET_ID, '&DAY', &ROUTE_ID, &CAT_CODE)
new 1: insert into fleet_header values(02, '10-apr-96', 101, 01)
1 row created.
SQL> /
Enter value for fleet_id: 03
Enter value for day: 10-apr-96
Enter value for route_id: 101
Enter value for cat_code: 01
old 1: insert into fleet_header values(&FLEET_ID, '&DAY', &ROUTE_ID, &CAT_CODE)
new 1: insert into fleet_header values(03, '10-apr-96', 101, 01)
1 row created.
158
SQL> /
Enter value for fleet_id: 04
Enter value for day: 10-apr-96
Enter value for route_id: 102
Enter value for cat_code: 02
old 1: insert into fleet_header values(&FLEET_ID, '&DAY', &ROUTE_ID, &CAT_CODE)
new 1: insert into fleet_header values(04, '10-apr-96', 102, 02)
1 row created.
SQL> /
Enter value for fleet_id: 05
Enter value for day: 10-apr-96
Enter value for route_id: 102
Enter value for cat_code: 03
old 1: insert into fleet_header values(&FLEET_ID, '&DAY', &ROUTE_ID, &CAT_CODE)
new 1: insert into fleet_header values(05, '10-apr-96', 102, 03)
1 row created.
SQL> /
Enter value for fleet_id: 06
Enter value for day: 10-apr-96
Enter value for route_id: 103
Enter value for cat_code: 04
old 1: insert into fleet_header values(&FLEET_ID, '&DAY', &ROUTE_ID, &CAT_CODE)
new 1: insert into fleet_header values(06, '10-apr-96', 103, 04)
1 row created.
Result: SQL> select * from fleet_header;
FLEET_ID DAY ROUTE_ID CAT_CODE
---------- --------- ---------- ----------
1 10-APR-96 101 1
2 10-APR-96 101 1
3 10-APR-96 101 1
4 10-APR-96 102 2
5 10-APR-96 102 3
6 10-APR-96 103 4
6 rows selected.
159
Assignment # 11
Insert into ticket_header the following values:
Fleet_id Ticket_no Doi Dot Time_travel Board_place Origin Destination Adults Children Total_fare Route_id
01 01 10-
apr-
96
10-
may-
96
15:00:00 Parrys Madras Madurai 1 1 60 101
02 02 12-
apr-
96
10-
may-
96
09:00:00 Kknagar Madurai Madras 2 1 60 102
03 03 21-
apr-
96
10-
may-
96
21:00:00 Cubbonpark Bangalore Madras 4 2 400 101
04 04 12-
apr-
96
10-
may-
96
10:00:00 Charminar Hyderabad Madras 10 0 500 103
05 250 10-
apr-
96
10-
may-
96
15:00:00 Parrys Madras Cochin 2 2 141 103
Query: SQL> insert into ticket_header values (&FLEET_ID, &TICKET_NO, '&DOI', '&DOT', '&TIME_TRAVEL', '&BOARD_PLACE', '&ORIGIN', '&DESTINATION', &ADULTS, &CHILDREN, &TOTAL_FARE, & ROUTE_ID); Enter value for fleet_id: 01 Enter value for ticket_no: 01 Enter value for doi: 10-apr-96 Enter value for dot: 10-may-96 Enter value for time_travel: 15:00:00 Enter value for board_place: Parrys Enter value for origin: Madras Enter value for destination: Madurai Enter value for adults: 1 Enter value for children: 1 Enter value for total_fare: 60 Enter value for route_id: 101 old 1: insert into ticket_header values (&FLEET_ID, &TICKET_NO, '&DOI', '&DOT', '&TIME_TRAVEL', '&BOARD_PLAC new 1: insert into ticket_header values (01, 01, '10-apr-96', '10-may-96', '15:00:00', 'Parrys', 'Madras', ' 1 row created. SQL> / Enter value for fleet_id: 02 Enter value for ticket_no: 02 Enter value for doi: 12-apr-96 Enter value for dot: 10-may-96 Enter value for time_travel: 09:00:00 Enter value for board_place: Kknagar Enter value for origin: Madurai Enter value for destination: Madras Enter value for adults: 2 Enter value for children: 1 Enter value for total_fare: 60 Enter value for route_id: 102
160
old 1: insert into ticket_header values (&FLEET_ID, &TICKET_NO, '&DOI', '&DOT', '&TIME_TRAVEL', '&BOARD_PLAC new 1: insert into ticket_header values (02, 02, '12-apr-96', '10-may-96', '09:00:00', 'Kknagar', 'Madurai', 1 row created. SQL> / Enter value for fleet_id: 03 Enter value for ticket_no: 03 Enter value for doi: 21-apr-96 Enter value for dot: 10-may-96 Enter value for time_travel: 20:00:00 Enter value for board_place: Cubbonpark Enter value for origin: Bangalore Enter value for destination: Madras Enter value for adults: 4 Enter value for children: 2 Enter value for total_fare: 400 Enter value for route_id: 101 old 1: insert into ticket_header values (&FLEET_ID, &TICKET_NO, '&DOI', '&DOT', '&TIME_TRAVEL', '&BOARD_PLAC new 1: insert into ticket_header values (03, 03, '21-apr-96', '10-may-96', '20:00:00', 'Cubbonpark', 'Bangal 1 row created. SQL> / Enter value for fleet_id: 04 Enter value for ticket_no: 04 Enter value for doi: 12-apr-96 Enter value for dot: 10-may-96 Enter value for time_travel: 10:00:00 Enter value for board_place: Charminar Enter value for origin: Hyderabad Enter value for destination: Madras Enter value for adults: 10 Enter value for children: 0 Enter value for total_fare: 500 Enter value for route_id: 103 old 1: insert into ticket_header values (&FLEET_ID, &TICKET_NO, '&DOI', '&DOT', '&TIME_TRAVEL', '&BOARD_PLAC new 1: insert into ticket_header values (04, 04, '12-apr-96', '10-may-96', '10:00:00', 'Charminar', 'Hyderab 1 row created. SQL> / Enter value for fleet_id: 05 Enter value for ticket_no: 250 Enter value for doi: 10-apr-96 Enter value for dot: 10-may-96 Enter value for time_travel: 15:00:00 Enter value for board_place: Parrys Enter value for origin: Madras Enter value for destination: Cochin Enter value for adults: 2 Enter value for children: 2 Enter value for total_fare: 141 Enter value for route_id: 103 old 1: insert into ticket_header values (&FLEET_ID, &TICKET_NO, '&DOI', '&DOT', '&TIME_TRAVEL', '&BOARD_PLAC new 1: insert into ticket_header values (05, 250, '10-apr-96', '10-may-96', '15:00:00', 'Parrys', 'Madras', 1 row created.
161
Result: SQL> select * from ticket_header;
FLEET_ID TICKET_NO DOI DOT TIME_TRA BOARD_PLACE ORIGIN DESTINATION ADULTS CHILDREN TOTAL_FARE ROUTE_ID
---------- ---------- --------- --------- -------- -------------- -------------- -------------- ------- -------- ---------- ----------
1 1 10-APR-96 10-MAY-96 15:00:00 Parrys Madras Madurai 1 1 60 101
2 2 12-APR-96 10-MAY-96 09:00:00 Kknagar Madurai Madras 2 1 60 102
3 3 21-APR-96 10-MAY-96 20:00:00 Cubbonpark Bangalore Madras 4 2 400 101
4 4 12-APR-96 10-MAY-96 10:00:00 Charminar Hyderabad Madras 10 0 500 103
5 250 10-APR-96 10-MAY-96 15:00:00 Parrys Madras Cochin 2 2 141 103
162
Assignment # 12
Insert into ticket_detail the following:
Ticket_no Name Sex Age Fare
01 Charu F 24 14.00
01 Latha F 10 15.55
02 Anand M 28 17.80
02 Gautham M 28 16.00
02 Bala M 9 17.65
05 sandeep M 30 18.00
Query: SQL> insert into ticket_detail values (&TICKET_NO, '&NAME', '&SEX', &AGE, &FARE); Enter value for ticket_no: 01 Enter value for name: Charu Enter value for sex: F Enter value for age: 24 Enter value for fare: 14.00 old 1: insert into ticket_detail values (&TICKET_NO, '&NAME', '&SEX', &AGE, &FARE) new 1: insert into ticket_detail values (01, 'Charu', 'F', 24, 14.00) 1 row created. SQL> / Enter value for ticket_no: 01 Enter value for name: Latha Enter value for sex: F Enter value for age: 10 Enter value for fare: 15.55 old 1: insert into ticket_detail values (&TICKET_NO, '&NAME', '&SEX', &AGE, &FARE) new 1: insert into ticket_detail values (01, 'Latha', 'F', 10, 15.55) 1 row created. SQL> / Enter value for ticket_no: 02 Enter value for name: Anand Enter value for sex: M Enter value for age: 28 Enter value for fare: 17.80 old 1: insert into ticket_detail values (&TICKET_NO, '&NAME', '&SEX', &AGE, &FARE) new 1: insert into ticket_detail values (02, 'Anand', 'M', 28, 17.80) 1 row created.
163
SQL> / Enter value for ticket_no: 02 Enter value for name: Gautham Enter value for sex: M Enter value for age: 28 Enter value for fare: 16.00 old 1: insert into ticket_detail values (&TICKET_NO, '&NAME', '&SEX', &AGE, &FARE) new 1: insert into ticket_detail values (02, 'Gautham', 'M', 28, 16.00) 1 row created. SQL> / Enter value for ticket_no: 02 Enter value for name: Bala Enter value for sex: M Enter value for age: 9 Enter value for fare: 17.65 old 1: insert into ticket_detail values (&TICKET_NO, '&NAME', '&SEX', &AGE, &FARE) new 1: insert into ticket_detail values (02, 'Bala', 'M', 9, 17.65) 1 row created. SQL> / Enter value for ticket_no: 05 Enter value for name: Sandeep Enter value for sex: M Enter value for age: 30 Enter value for fare: 18.00 old 1: insert into ticket_detail values (&TICKET_NO, '&NAME', '&SEX', &AGE, &FARE) new 1: insert into ticket_detail values (05, 'Sandeep', 'M', 30, 18.00) 1 row created.
Result: SQL> select * from ticket_detail; TICKET_NO NAME S AGE FARE ---------- -------------------- - ---------- ---------- 1 Charu F 24 14 1 Latha F 10 15.55 2 Anand M 28 17.8 2 Gautham M 28 16 2 Bala M 9 17.65 5 Sandeep M 30 18 6 rows selected.
164
Assignment # 13
Alter the table route_header to add a column comments with datatype as long.
Query: SQL> alter table route_header add comments long;
Table altered.
Result: SQL> desc route_header;
Name Null? Type
----------------------------------------- -------- ----------------------------
ROUTE_ID NUMBER(5)
ROUTE_NO NUMBER(5)
CAT_CODE NUMBER(5)
ORIGIN VARCHAR2(20)
DESTINATION VARCHAR2(20)
FARE NUMBER(7,2)
DISTANCE NUMBER(3)
CAPACITY NUMBER(3)
COMMENTS LONG
Assignment # 14
Describe route_header
Query: SQL> desc route_header;
Result: Name Null? Type
----------------------------------------- -------- ----------------------------
ROUTE_ID NUMBER(5)
ROUTE_NO NUMBER(5)
CAT_CODE NUMBER(5)
ORIGIN VARCHAR2(20)
DESTINATION VARCHAR2(20)
FARE NUMBER(7,2)
DISTANCE NUMBER(3)
CAPACITY NUMBER(3)
COMMENTS LONG
165
Assignment # 15
Display only distinct category code from the table route_header order in the descending manner.
Query: SQL> select distinct cat_code from route_header order by cat_code desc;
Result:
CAT_CODE
----------
4
3
2
1
Assignment # 16
Alter the table to modify the length of the column distance in the table route_header to 4.
Query: SQL> alter table route_header modify distance number(4);
Table altered.
Result: SQL> desc route_header;
Name Null? Type
----------------------------------------- -------- ----------------------------
ROUTE_ID NUMBER(5)
ROUTE_NO NUMBER(5)
CAT_CODE NUMBER(5)
ORIGIN VARCHAR2(20)
DESTINATION VARCHAR2(20)
FRAME NUMBER(7,2)
DISTANCE NUMBER(4)
CAPACITY NUMBER(3)
166
Assignment # 17
Create table route_detail – route_id number (5), place_id number (5), nonstop char (1).
Query: SQL> create table route_detail (route_id number(5),place_id number(5),nonstop
char(1));
Table created.
Result: SQL> desc route_detail;
Name Null? Type
----------------------------------------- -------- ----------------------------
ROUTE_ID NUMBER(5)
PLACE_ID NUMBER(5)
NONSTOP CHAR(1)
Assignment # 18
Insert into table route_detail the following rows:
Route_id Place_id Nonstop
105 01 n
102 02 s
106 01 s
108 05 n
Query: SQL> insert into route_detail values (&NUMBER, &PLACE_ID, '&NONSTOP');
Enter value for number: 105
Enter value for place_id: 01
Enter value for nonstop: n
old 1: insert into route_detail values (&NUMBER, &PLACE_ID, '&NONSTOP')
new 1: insert into route_detail values (105, 01, 'n')
1 row created.
167
SQL> /
Enter value for number: 102
Enter value for place_id: 02
Enter value for nonstop: s
old 1: insert into route_detail values (&NUMBER, &PLACE_ID, '&NONSTOP')
new 1: insert into route_detail values (102, 02, 's')
1 row created.
SQL> /
Enter value for number: 106
Enter value for place_id: 01
Enter value for nonstop: s
old 1: insert into route_detail values (&NUMBER, &PLACE_ID, '&NONSTOP')
new 1: insert into route_detail values (106, 01, 's')
1 row created.
SQL> /
Enter value for number: 108
Enter value for place_id: 05
Enter value for nonstop: n
old 1: insert into route_detail values (&NUMBER, &PLACE_ID, '&NONSTOP')
new 1: insert into route_detail values (108, 05, 'n')
1 row created.
Result: SQL> select * from route_detail;
ROUTE_ID PLACE_ID N
---------- ---------- -
105 1 n
102 2 s
106 1 s
108 5 n
168
Assignment # 19
Insert into the above table the following values: 106, 02, n.
Query:
SQL> insert into route_detail values(106,02,'n');
1 row created.
Result:
SQL> select * from route_detail;
ROUTE_ID PLACE_ID N
---------- ---------- -
105 1 n
102 2 s
106 1 s
108 5 n
106 2 n
Assignment # 20
Change the nonstop to “N”, of the route_detail where the route_id is 102
Query: SQL> update route_detail set nonstop='n' where route_id=102;
1 row updated.
Result: SQL> select * from route_detail;
ROUTE_ID PLACE_ID N
---------- ---------- -
105 1 n
102 2 n
106 1 s
108 5 n
106 2 n
169
Assignment # 21
Delete the row whose route_id is 102
Query: SQL> delete from route_detail where route_id=102;
1 row deleted.
Result: SQL> select * from route_detail;
ROUTE_ID PLACE_ID N
---------- ---------- -
105 1 n
106 1 s
108 5 n
106 2 n
Assignment # 22
Display only those routes that originates in madras and terminate at cochin
Query: SQL> select * from route_header where origin='Madras' and destination='Cochin';
Result:
ROUTE_ID ROUTE_NO CAT_CODE ORIGIN DESTINATION FRAME DISTANCE CAPACITY
---------- ---------- ---------- --------- -------------- ------ ---------- ----------
108 41 4 Madras Cochin 47 576 50
170
Assignment # 23
Update the table route_header to set the distance between madras and madurai to be 300.
Query: SQL> update route_header set distance=300 where origin in ('Madras', 'Madurai') and
destination in (
'Madras', 'Madurai');
2 rows updated.
Result SQL> select * from route_header;
ROUTE_ID ROUTE_NO CAT_CODE ORIGIN DESTINATION FRAME DISTANCE CAPACITY
---------- ---------- ---------- ---------- ------------ ------ ---------- ----------
101 33 1 Madurai Madras 35 300 50
102 25 2 Trichy Madurai 40 159 50
103 15 3 Thanjavur Madurai 59 140 50
104 36 4 Madras Bangalore 79 375 50
105 40 1 Bangalore Madras 80 375 50
106 38 2 Madras Madurai 39 300 50
107 39 3 Hyderabad Madras 50 430 50
108 41 4 Madras Cochin 47 576 50
8 rows selected.
Assignment # 24
Delete only those rows that have the destination as Bangalore and the origin as madras.
Query: SQL> delete from route_header where origin='Madras' and destination='Bangalore';
1 row deleted.
Result: SQL> select * from route_header;
ROUTE_ID ROUTE_NO CAT_CODE ORIGIN DESTINATION FRAME DISTANCE CAPACITY
---------- ---------- ---------- ---------- ------------ ------ ---------- ----------
101 33 1 Madurai Madras 35 300 50
102 25 2 Trichy Madurai 40 159 50
103 15 3 Thanjavur Madurai 59 140 50
105 40 1 Bangalore Madras 80 375 50
106 38 2 Madras Madurai 39 300 50
107 39 3 Hyderabad Madras 50 430 50
108 41 4 Madras Cochin 47 576 50
7 rows selected.
171
Assignment # 25
Display only those rows from route_header whose origin begins with ‘M’.
Query: SQL> select * from route_header where origin like 'M%';
Result: SQL> select * from route_header;
ROUTE_ID ROUTE_NO CAT_CODE ORIGIN DESTINATION FRAME DISTANCE CAPACITY
---------- ---------- ---------- ---------- ------------ ------ ---------- ----------
101 33 1 Madurai Madras 35 300 50
106 38 2 Madras Madurai 39 300 50
108 41 4 Madras Cochin 47 576 50
3 rows selected.
Assignment # 26
Display only those rows whose fare ranges between 30 and 50.
Query: SQL> select * from route_header where frame between 30 and 50;
Result: SQL> select * from route_header;
ROUTE_ID ROUTE_NO CAT_CODE ORIGIN DESTINATION FRAME DISTANCE CAPACITY
---------- ---------- ---------- ---------- ------------ ------ ---------- ----------
101 33 1 Madurai Madras 35 300 50
102 25 2 Trichy Madurai 40 159 50
106 38 2 Madras Madurai 39 300 50
107 39 3 Hyderabad Madras 50 430 50
108 41 4 Madras Cochin 47 576 50
5 rows selected.
172
Assignment # 27
Display the fare and the origin for those route_no which are greater than 15.
Query: SQL> select frame, origin from route_header where route_no>15;
Result: FRAME ORIGIN
---------- --------------------
35 Madurai
40 Trichy
80 Bangalore
39 Madras
50 Hyderabad
47 Madras
6 rows selected.
Assignment # 28
Display all details of a place whose name begins with ‘M’.
Query: SQL> select * from place_header where place_name like 'M%';
Result: PLACE_ID PLACE_NAME PLACE_ADDRESS BUS_STATIO
---------- -------------------- ------------------------------ ----------
1 Madras 10, ptc road Parrys
2 Madurai 21, canalbank road Kknagar
Assignment # 29
Display the details of places whose names begins with ‘A’.
Query: SQL> select * from place_header where place_name like 'A%';
Result: no rows selected
173
Assignment # 30
Create pseudo table with the same structure as the table category_header and insert rows into the
table using the select clause.
Query: SQL> create table pseudo as(select * from category_header);
Table created.
Result: SQL> select * from category_header;
CAT_CODE CAT_DESC
---------- --------------------
1 Super deluxe
2 Deluxe
3 Super fast
4 Normal
Assignment # 31
Display the date two months after the date of issue of the ticket
Query: SQL> select add_months (doi, 2) from ticket_header;
Result: ADD_MONTH
---------
10-JUN-96
12-JUN-96
21-JUN-96
12-JUN-96
10-JUN-96
174
Assignment # 32
Display only those place names that begin with ‘M’ and replace them with ‘V’.
Query: SQL> select translate (place_name, 'M', 'V') from place_header where place_name
like 'M%';
Result: TRANSLATE(PLACE_NAME
--------------------
Vadras
Vadurai
Assignment # 33
Display only 3 characters from the third character in the names of the traveler.
Query: SQL> select substr (name, 3, 3) from ticket_detail;
Result:
SUB
---
aru
tha
and
uth
la
nde
6 rows selected.
175
Assignment # 34
Select distinct ticket numbers from both ticket_header and ticket_detail.
Query: SQL> (select ticket_no from ticket_header) union all(select ticket_no from
ticket_detail);
Result: TICKET_NO
----------
1
2
3
4
250
1
1
2
2
2
5
11 rows selected.
Assignment # 35
Select only the common fleet_ids that are present in the fleet_header and ticket_header.
Query: SQL> (select fleet_id from fleet_header) intersect (select fleet_id from
ticket_header);
Result: FLEET_ID
----------
1
2
3
4
5
176
Assignment # 36
Select row from ticket_detail such that the ticket numbers exceed the average of the total fare and the
origin is ‘Madras’.
Query: SQL> select * from ticket_detail where ticket_no>all (select avg (total_fare) from
ticket_header where origin= 'Madras');
Result: no rows selected