Solution

Published on June 2016 | Categories: Documents | Downloads: 24 | Comments: 0 | Views: 156
of 41
Download PDF   Embed   Report

Comments

Content

Help - Search - Members - Calendar Full Version MCSL-025 - Java Lab Session

IGNOU MCA STUDENTS' FORUM > MCSL-025 :: Lab (based on MCS-021, 022, 023 & 024) Pages: 1, 2 LEFTY August 13, 2006 05:55 pm Session 1: Exercise 4: public class Marks { float hn,eng,phy,chem,math,avg; public Marks() { hn=55; eng=61; phy=79; chem=50; math=88; } public void Calc() { avg=(hn+eng+phy+chem+math)/5; System.out.println("Average marks is :"+avg); } public static void main(String args[]) { Marks Z=new Marks(); Z.Calc(); } } Anubhav September 14, 2006 02:38 am In the matrix multiplicataion I just created a program to input values to the ma trix and print it. The program compiled fine but while executing I got ARRayExce ptionoutofbounds. I used the try and catch but it made the program wrong. Can an yone help me ajeet September 14, 2006 01:34 pm Guys I have'nt understood why do we need to make objects of a class when we have only one class.I think we can access it directly also.Can we not make the progr am as done in C,all in one class without objects.Yes offcourse, it will voilate the object oriented nature of java but is there any other reason? Anubhav September 17, 2006 07:14 pm Hi Guys, Following are the first seven programs of the java lab assignments: 1. class LabProgam1 { public static void main(String args[]) { int Length, width, Area; Length= 200; width=400; Area=Length*width;

System.out.println("The Length of the Rectangle is"+Length+"cms"); System.out.println("\n The width of the Rectangle is"+width+"cms"); System.out.println("\n The area of the Rectangle is"+Area+"sq.cms"); } } ---------------------------------------------------------------------------------------2. class LabProgram2 { public static void main(String args[]) { int a=10,b=5,S1=0,S2=0,S3=0,S4=0; S1=(a<<2)+(b>>2); //S2=(a)||(b>0); S3=(a+b*100)/10; S4=a&b; System.out.println("\n a= " + a + " b = " +; System.out.println("\n (a << 2) + (b >> 2) =" +S1); System.out.println("\n ((a)||(b>0)="+S2); System.out.println("\n (a + b * 100 ) / 10=" +S3); System.out.println("\n a & b =" + S4); } } ----------------------------------------------------------------------------------------3. class LabProgram3 { public static void main(String args[]) { int i,j,n; for(n=11;n<=19;n++) { for(i=2;i<=n;i++) { j=n%i; if(j==0&&i==n) { System.out.println("\n The number"+ n +"is prime"); break; } else if(j==0) { System.out.println("\n The number"+ n +"is not prime"); break; } else continue; } } } } -------------------------------------------------------------------------------4.

class LabProgram4 { public static void main(String args[]) { float mark_math=75; float mark_physics=76; float mark_chemistry=78; float mark_english=88; float mark_hindi=90; float mark_geo=88; float mark_total=mark_math+mark_physics+mark_chemistry+mark_hindi+mark_geo; float mark_avg=(mark_total)/6; System.out.println("\n The marks obtained in Maths = "+ mark_math); System.out.println("\n The marks obtained in Physics ="+ mark_physics); System.out.println("\n The marks obtained in Chemistry ="+ mark_chemistry); System.out.println("\n The marks obtained in English = "+ mark_english); System.out.println("\n The marks obtained in Hindi ="+ mark_hindi); System.out.println("\n The marks obtained in Geology"+ mark_geo); System.out.println("\n Total marks obtained = "+ mark_total); System.out.println("\n Average of the marks = "+ mark_avg); } } --------------------------------------------------------------------------------------5. import java.io.DataInputStream; class LabProgram5 { public static void main(String args[]) throws Exception { DataInputStream in=new DataInputStream(System.in); int i,j,k; int A[][] = new int[3][3]; int B[][] = new int[3][4]; int AxB[][] = new int[3][4]; System.out.println("Please enter the values of Matrix A "); for(i=0;i<3;i++) { for(j=0;j<3;j++) { System.out.println("Enter values for Matrix A location ["+i+"]["+j+"]"); A[i][j]=Integer.parseInt(in.readLine()); } } System.out.println("Please enter the values of Matrix B"); for(i=0;i<3;i++) { for(j=0;j<4;j++) { System.out.println("Enter values for Matrix B location ["+i+"]["+j+"]"); B[i][j]=Integer.parseInt(in.readLine()); } }

for(i=0;i<3;i++) { for(j=0;j<4;j++) { AxB[i][j]=0; for(k=0;k<3;k++) { AxB[i][j]=AxB[i][j]+A[i][k]*B[k][j]; } } } System.out.println("The First matrix is"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { System.out.print(A[i][j]+" "); } System.out.println("\n"); } System.out.println("The Second matrix is"); for(i=0;i<3;i++) { for(j=0;j<4;j++) { System.out.print(B[i][j]+" "); } System.out.println("\n"); } System.out.println("The product matrix is"); for(i=0;i<3;i++) { for(j=0;j<4;j++) { System.out.print(AxB[i][j]+" "); } System.out.println("\n"); } } }

---------------------------------------------------------------------------------6. import java.io.DataInputStream; class LabProgram6 {

public static void main(String args[]) { DataInputStream in= new DataInputStream(System.in); int n=0,i=0,r=0,sum=0,l; try { System.out.println("Enter a number"); n=Integer.parseInt(in.readLine()); } catch( Exception e) {} int Ar[]=new int[5]; int n1=n; for(i=0;i<=4;i++) { r=n%10; Ar[i]=r; n=n/10; l=5-i; System.out.println("Digit No."+ l +"=" + Ar[i]); sum=sum+Ar[i]; } System.out.println("The sum of digits of " + n1 +" = " + sum); } }

---------------------------------------------------------------------------------------7. class Rectangle { double len,width; String col; void set_length(double L) { len=L; } void set_width(double W) { width=W; } void set_color(String clr) { col=clr; } double find_area() {return(len*width); } }

class LabProgram7 { public static void main(String args[])

{ double length,width,area,area1,area2; String color1,color2; Rectangle R1 = new Rectangle(); R1.set_length(10); R1.set_width(15); R1.set_color("blue"); area1=R1.find_area(); Rectangle R2 = new Rectangle(); R2.set_length(10); R2.set_width(15); R2.set_color("Red"); area2=R2.find_area(); color1=R1.col; color2=R2.col; System.out.println("The area of Rectangle 1="+ area1); System.out.println("The color of Rectangle 1="+ color1); System.out.println("The area of Rectangle 2="+ area2); System.out.println("The color of Rectangle 2="+ color2); if((area1==area2)&&(color1.equals(color2))) {System.out.println("Matching Rectangles"); } else { System.out.println("Non matching Rectangle"); } } } ------------------------------------------------------------------------------------pintu_majumder November 05, 2006 12:37 pm Programme no 3.1 QUOTE

class rect { int l,b; int area; String color; public void Set_Length(int x) { l=x; } public void Set_breath(int y) { b=y; } public void Set_area() {

area=l*b; } public void Set_color(String s) { color=new String(s); } public int IsEqual(rect r) { if((r.area==area)&&(r.color.equals(color))) return (1); else return (0); } } public class abc { public static void main(String args[]) { rect ob1=new rect(); rect ob2=new rect(); ob1.Set_Length(2); ob1.Set_breath(3); ob1.Set_color("Blue"); ob2.Set_Length(6); ob2.Set_breath(1); ob2.Set_color("Blue"); int result=ob1.IsEqual(ob2); if(result==0) System.out.println("False"); else System.out.println("True"); } } vaby December 19, 2006 06:43 am well anubhav has given programs upto session 3 exercise1.... continuing further... 3.2 - the class names suggest the session and excercise number... Q0302 CODE class Account { String name; String address; String ac_type; int ac_number; double init_balance; double cur_balance; Account(String a, int b, double c) {

name = a; ac_number = b; init_balance = c; } Account(String a, String b, String c, int d, double e) { name = a; ac_number = d; address = b; ac_type = c; cur_balance = e; } void Deposit(double amt) { if(init_balance > 0) { cur_balance = init_balance+amt; } else { cur_balance += amt; } } void Withdraw(double amt) { if(init_balance > 0) { cur_balance = init_balance - amt; } else { cur_balance -= amt; } } double Get_Balance() { return cur_balance; } } class Q0302 { public static void main(String[] args) { Account ac1 = new Account("ABC", 123, 12000); Account ac2 = new Account("ASD", "New Delhi", "SB", 124, 10000); double bal; ac1.Deposit(500); bal = ac1.Get_Balance(); System.out.println("Name: "+ac1.name); System.out.println("A/c No: "+ac1.ac_number); System.out.println("Initial Balance: "+ac1.init_balance); System.out.println("Balance after Deposit: "+bal); System.out.println(); ac2.Deposit(1000); bal = ac2.Get_Balance(); System.out.println("Name: "+ac2.name); System.out.println("Address: "+ac2.address); System.out.println("Type of Account: "+ac2.ac_type); System.out.println("A/c No: "+ac2.ac_number); System.out.println("Initial Balance: "+ac2.init_balance);

System.out.println("Balance after Deposit: "+bal); } } Q0303 CODE class Stack { int stck[] = new int[10]; int top; Stack() { top = -1; } void push(int item) { if(top == 9) System.out.println("Stack is full."); else stck[++top] = item; } int pop() { if (top < 1) { System.out.println("Stack is underflow."); return 0; } else { return stck[--top]; } } } class q0303 { public static void main(String args[]) { Stack s1 = new Stack(); Stack s2 = new Stack(); for(int i = 0; i < 10; i++) s1.push(i); for(int i = 10; i < 20; i++) s2.push(i); System.out.println("Numbers in first Stack:"); for(int i = 0; i < 10; i++) System.out.println(s1.pop()); System.out.println("Numbers in second Stack:"); for(int i = 0; i < 10; i++) System.out.println(s2.pop()); } } vaby December 19, 2006 06:47 am q0401

CODE class parent { private void show1() { System.out.println("This will not be inheritted."); } public void show2() { System.out.println("This will be inheritted by child class."); } } class child extends parent { void show3() { System.out.println("This is in child class."); } } class q0401 { public static void main(String args[]) { child c = new child(); //c.show1(); c.show2(); c.show3(); } } q0402 CODE This question has been taken from study material only Answer of this question is in our study material page no - 39 block no - 2 q0403 CODE class Worker{ String name; double s_rate; void ComPay(int hours){ System.out.println("No data available."); } } class DailyWorker extends Worker{ DailyWorker(String n, double r){ name = n; s_rate = r; } void ComPay(int hours){ double amt; System.out.println();

System.out.println("*** Daily Wages Worker System.out.println(); System.out.println("Worker Name: "+ name); System.out.println("Worked Hours: "+ hours); amt = s_rate * hours; System.out.println(" ========"); System.out.println("Total Pay: "+ amt); System.out.println(" ========"); System.out.println(); } }

***");

class SalariedWorker extends Worker{ SalariedWorker(String n, double r){ name = n; s_rate = r; } void ComPay(int hours){ double amt; System.out.println(); System.out.println("*** Salaried Worker ***"); System.out.println(); System.out.println("Worker Name: "+ name); System.out.println("Worked Hours: "+ hours); amt = s_rate * 40; System.out.println(" ========"); System.out.println("Total Pay: "+ amt); System.out.println(" ========"); System.out.println(); } } class q0403{ public static void main(String args[]){ DailyWorker dw = new DailyWorker("Deepak",50.00); SalariedWorker sw = new SalariedWorker("Abhishek",50.00); dw.ComPay(38); sw.ComPay(30); } } q0404 CODE class trunkCall { float time; float amount; float Calculation() { return 0; } } class ordinary extends trunkCall { ordinary(float t) { time = t;

} float Calculation() { if(time <= 1) { amount = time * 3; } else if(time <= 5) { amount = (time * 3)-((time*3)*5/100); } else if(time > 5) { amount = (time * 3)-((time*3)*10/100); } return amount; } } class urgent extends trunkCall { urgent(float t) { time = t; } float Calculation() { if(time <= 1) { amount = time * 4; } else if(time <= 5) { amount = (time * 4)-((time*4)*5/100); } else if(time > 5) { amount = (time * 4)-((time*4)*10/100); } return amount; } } class lightning extends trunkCall { lightning(float t) { time = t; } float Calculation() { if(time <= 1) { amount = time * 5; } else if(time <= 5) { amount = (time * 5)-((time*5)*5/100); } else if(time > 5)

{ amount = (time * 5)-((time*5)*10/100); } return amount; } } class q0404 { public static void main(String args[]) { float amt; ordinary o1 = new ordinary(1); ordinary o2 = new ordinary(4); ordinary o3 = new ordinary(9); System.out.println(); System.out.println("Ordinary Call Charges"); amt = o1.Calculation(); System.out.println("for " +o1.time+ " mins is: amt = o2.Calculation(); System.out.println("for " +o2.time+ " mins is: amt = o3.Calculation(); System.out.println("for " +o3.time+ " mins is: urgent u1 = new urgent(1); urgent u2 = new urgent(4); urgent u3 = new urgent(9); System.out.println(); System.out.println("Urgent Call Charges"); amt = u1.Calculation(); System.out.println("for " +u1.time+ " mins is: amt = u2.Calculation(); System.out.println("for " +u2.time+ " mins is: amt = u3.Calculation(); System.out.println("for " +u3.time+ " mins is: lightning l1 = new lightning(1); lightning l2 = new lightning(4); lightning l3 = new lightning(9); System.out.println(); System.out.println("Lightning Call Charges"); amt = l1.Calculation(); System.out.println("for " +l1.time+ " mins is: amt = l2.Calculation(); System.out.println("for " +l2.time+ " mins is: amt = l3.Calculation(); System.out.println("for " +l3.time+ " mins is: } } vaby December 19, 2006 06:55 am q0501 QUOTE CODE import Balance.Account; class q0501 { public static void main(String args[]) { Account a = new Account();

"+amt); "+amt); "+amt);

"+amt); "+amt); "+amt);

"+amt); "+amt); "+amt);

a.Display_Balance(); } } Imp note: CODE //part of q0501 //This file(Account.java) should be put into folder named Balance. package Balance; public class Account { public void Display_Balance() { System.out.println("This is the Balance of Account in Balance Package."); } } vaby December 19, 2006 06:58 am Q0502 not done this is q0503 QUOTE interface iface { void division(int a, int b ); void modules(int a, int b ); } class ifaceTest implements iface { public void division(int a, int b ) { System.out.println("After Division, the number is: "+ a/b); } public void modules(int a, int b ) { System.out.println("Modules of the numbers is: "+ a%b ); } } class q0503 { public static void main(String args[]) { ifaceTest i = new ifaceTest(); i.division(125, 5); i.modules(125, 6); } } q0504 QUOTE interface Student

{ void Display_Grade(); void Attendance(); } class PG_Student implements Student { public void Display_Grade() { System.out.println("Grade of PG Student should be A+"); } public void Attendance() { System.out.println("Attandance of PG Student should be 75%"); } } class UG_Student implements Student { public void Display_Grade() { System.out.println("Grade of UG Student should be A"); } public void Attendance() { System.out.println("Attandance of UG Student should be 70%"); } } class q0504 { public static void main(String args[]) { PG_Student pg = new PG_Student(); UG_Student ug = new UG_Student(); pg.Display_Grade(); pg.Attendance(); System.out.println(); ug.Display_Grade(); ug.Attendance(); } } vaby December 19, 2006 07:05 am q0601 QUOTE class q0601 { public static void main(String args[]) { String name[] = {"deep","jitu","abhi","shashi","mani"}; int roll[] = {101,102,103,104,105}; try { for(int i = 0; i<6; i++) { System.out.println("Name: "+name[i]+" Roll: "+roll[i]); } }

catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array out of limit."); } } } q0602 QUOTE class q0602 { public static void main(String args[]) { int a = 10; int b = 2; int c; try { c = a/b; System.out.println("The result is: "+c); } catch(ArithmeticException e) { System.out.println("Division by zero"); } } } q0603 QUOTE class MyException extends Exception { private int value; MyException(int a) { value = a; } public String toString() { return("MyException for value ["+value+"]"); } } class q0603 { static void calculate(int a) throws MyException { System.out.println("Call calculate method [" +a+ "]"); if(a>10) throw new MyException(a); System.out.println("Normal exit."); } public static void main(String args[]) { try { calculate(Integer.parseInt(args[0]));

} catch(MyException e) { System.out.println("MyException caught: "+e); } } } santanu December 19, 2006 07:41 am Great going vaby. I'd be posting the DBMS sessions soon and some Java too. One o f my friends is working on the Data Structures... he'd post some too. vaby December 19, 2006 07:06 pm q0701 QUOTE class ThreadEx implements Runnable { public void run() { for(int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName()); } } } public class q0701 { public static void main(String args[]) { ThreadEx te = new ThreadEx(); Thread t1 = new Thread(te, "One"); Thread t2 = new Thread(te, "Two"); Thread t3 = new Thread(te, "Three"); Thread t4 = new Thread(te, "Four"); Thread t5 = new Thread(te, "Five"); t1.setPriority(Thread.MAX_PRIORITY); t2.setPriority(t1.getPriority() - 2); t3.setPriority(Thread.NORM_PRIORITY); t4.setPriority(t5.getPriority() + 2); t5.setPriority(Thread.MIN_PRIORITY); try { t1.start(); t1.sleep(1000); t2.start(); t2.sleep(1000); } catch(InterruptedException e) { System.out.println(e); } t3.start(); t4.start(); t5.start(); System.out.println("Thread One is alive [Y/N]: "+ t1.isAlive()); } }

Q0702 QUOTE class Call { synchronized void show(String msg) { System.out.println("[ " +msg+ " ]"); } } class Test implements Runnable { String msg; Call c; Thread t; public Test(Call a, String s) { c = a; msg = s; t = new Thread(this); t.start(); } public void run() { c.show(msg); } } class q0702 { public static void main(String args[]) { Call T = new Call(); Test r1 = new Test(T,"ONE"); Test r2 = new Test(T,"TWO"); Test r3 = new Test(T,"THREE"); Test r4 = new Test(T,"FOUR"); Test r5 = new Test(T,"FIVE"); Test r6 = new Test(T,"SIX"); Test r7 = new Test(T,"SEVEN"); Test r8 = new Test(T,"EIGHT"); Test r9 = new Test(T,"NINE"); Test r10 = new Test(T,"TEN"); try { r1.t.join(); r2.t.join(); r3.t.join(); r4.t.join(); r5.t.join(); r6.t.join(); r7.t.join(); r8.t.join(); r9.t.join(); r10.t.join(); } catch(InterruptedException e)

{ System.out.println("Interrupted."); } } } q0703 QUOTE class Thread1 implements Runnable { int i; public void run() { System.out.println("\nOdd Numbers: "); for(i = 0; i < 10; i++) { if(i % 2 == 0) { continue; } System.out.print(i+ "\t"); } } } class Thread2 implements Runnable { int j; public void run() { System.out.println("\nEven Numbers: "); for(j = 1; j <= 10; j++) { if(j % 2 != 0) { continue; } System.out.print(j+ "\t"); } } } public class q0703 { public static void main(String args[]) { Thread1 te1 = new Thread1(); Thread2 te2 = new Thread2(); Thread t1 = new Thread(te1); Thread t2 = new Thread(te2); t1.start(); t2.start(); } } q0704

QUOTE class Call { synchronized void show(String msg) { System.out.println("[ " +msg+ " ]"); } } class Test implements Runnable { String msg; Call c; Thread t; public Test(Call a, String s) { c = a; msg = s; t = new Thread(this); t.start(); } public void run() { c.show(msg); } } class q0704 { public static void main(String args[]) { Call T = new Call(); Test r1 = new Test(T,"THIS "); Test r2 = new Test(T,"IS"); Test r3 = new Test(T,"SYNCHRONIZATION"); Test r4 = new Test(T,"TEST."); try { r1.t.join(); r2.t.join(); r3.t.join(); r4.t.join(); } catch(InterruptedException e) { System.out.println("Interrupted."); } } } vaby December 19, 2006 08:56 pm q0801 QUOTE class q0801 { public static void main(String args[]) { String s = new String("Deepak Kumar"); int l = s.length();

int a = 0; int i; System.out.println("Length is: "+l); String rep = new String("YES"); if(s.indexOf('a')>0) { System.out.println("EXISTANCE OF [a]: YES"); } System.out.println("LOCATIONS OF OCCURANCE:"); for(i=0;i<l;i++) { if(s.charAt(i)=='a') { a += 1; System.out.println(i); } } System.out.println("NUMBER OF OCCURANCE:"+a); } }

q0802 QUOTE class q0802 { public static void main(String args[]) { StringBuffer s = new StringBuffer(args[0]); s.reverse(); System.out.println(s); String s1 = new String(s); System.out.println(s1.toUpperCase()); } }

q0803 QUOTE class q0803 { public static void main(String args[]) { String s = "this is line one\n"+ "this is second line\n"+ "this is line no three"; System.out.println("The string is: \n" +s); System.out.println("First occurance of character [t] is: " +s.indexOf("t")); System.out.println("Last occurance of character [t] is: " +s.lastIndexOf("t")); System.out.println("First occurance of substring [line] is: " +s.indexOf("line") ); System.out.println("Last occurance of substring [line] is: " +s.lastIndexOf("lin e")); } }

q0804 QUOTE import java.io.*; class q0804 { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter Lines of text. Enter 'stop' to exit."); do { str = br.readLine(); System.out.println(str.toUpperCase()); }while(!str.equals("stop")); } } q0805 QUOTE import java.io.*; class q0805 { public static void main(String args[]) throws IOException { int i; FileInputStream fin; try { fin = new FileInputStream(args[0]); } catch(FileNotFoundException e) { System.out.println("File not found."); return; } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Wrong number."); return; } do { i = fin.read(); if(i != -1) System.out.print((char) i); }while(i != -1); fin.close(); } } q0806 QUOTE import java.io.*; class q0806

{ public static void main(String args[]) throws IOException { int i; FileInputStream fin; FileOutputStream fout; try { fin = new FileInputStream("in.txt"); System.out.println("Input file opened."); } catch(FileNotFoundException e) { System.out.println("File not found."); return; } try { fout = new FileOutputStream("out.txt"); System.out.println("Output file created."); } catch(FileNotFoundException e) { System.out.println("File not found."); return; } do { i = fin.read(); if(i != -1) fout.write(i); }while(i != -1); fin.close(); fout.close(); System.out.println("File renamed."); } } vaby December 21, 2006 10:18 am q0901 QUOTE import java.awt.*; import java.awt.event.*; import java.applet.*; /*Write the following code in "q0901.html" file <applet code = "q0901" width = 300 height = 50></applet>*/ public class q0901 extends Applet implements ActionListener { int c = 0; TextField nam, adr, resl; Button find; public void init() { setBackground(Color.cyan); setForeground(Color.red);

Label nm = new Label("Name: ", Label.RIGHT); Label ad = new Label("Address: ", Label.RIGHT); nam = new TextField(10); adr = new TextField(15); resl = new TextField(5); find = new Button("Find"); add(nm); add(nam); add(ad); add(adr); add(find); add(resl); find.addActionListener(this); } public void actionPerformed(ActionEvent ae) { String st = ae.getActionCommand(); String n = nam.getText(); String a = adr.getText(); int x = n.length(); int y = a.length(); c = x+y; if(st.equals("Find")) { resl.setText(""+c); } repaint(); } }

q0902 QUOTE import java.awt.*; import java.applet.*; //<applet code = "q0902" width = 300 height = 100></applet> public class q0902 extends Applet { public void paint(Graphics g) { Color c1 = new Color(255,100,100); Color c2 = new Color(0,25,255); g.setColor(c1); g.fillRect(10,10,100,100); g.setColor(c2); g.drawString("This is colored String",150,150); } } q0905 QUOTE import java.awt.*; import java.applet.*; import java.awt.event.*; //<applet code = "q0905" width = 300 height = 100></applet> public class q0905 extends Applet implements ActionListener {

TextArea t1; TextField t2; Label l = new Label(" "); String val = "There are two ways of constructing a software design.\n"+ "One way is to make it so simple\n"+ "And the other way is to make it so complicated\n"+ "that there are no obvious deficiencies.\n\n"+ " - C.A.R.Hoare\n\n."; public void init() { t1 = new TextArea(val, 10, 30); t2 = new TextField(10); add(t1); add(t2); add(l); t2.addActionListener(this); } public void actionPerformed(ActionEvent ae) { String st = ae.getActionCommand(); String s = t2.getText(); int k = val.indexOf(s); if(k >=0) l.setText("Found"); else l.setText("Not Found"); repaint(); } } vaby December 21, 2006 10:21 am q1001 QUOTE import java.net.*; class q1001 { public static void main(String args[]) throws UnknownHostException { InetAddress a1[] = InetAddress.getAllByName("www.ignou.ac.in"); InetAddress a2[] = InetAddress.getAllByName("www.indiatimes.com"); InetAddress a3[] = InetAddress.getAllByName("www.rediff.com"); InetAddress a4[] = InetAddress.getAllByName("www.apple.com"); System.out.println(a1[0]); System.out.println(a2[0]); System.out.println(a3[0]); System.out.println(a4[0]); } } q1002 QUOTE import java.applet.*; import java.awt.*; import java.net.*; /*<applet code = "q1002" width = 200 height = 100> <param name = nam value = "Deepak">

<param name = age value = 25></applet>*/ public class q1002 extends Applet { String nam; int age; public void start() { String param; nam = getParameter("nam"); if(nam == null) nam = "Not Found."; param = getParameter("age"); try { if(param != null) age = Integer.parseInt(param); else age = 0; } catch(NumberFormatException e) { age = -1; } } public void paint(Graphics g) { g.drawString(nam + " is " + age + " years old.",0,10); URL url = getCodeBase(); g.drawString("URL of file is: " +url.toString(),0,30); } } vaby December 21, 2006 10:31 am Friends - our Java lab manual programs are almost ready... only 5 programs left to b completed they are... session 6 : exercise 4 session 9 : exercise 3 and 4 session 10 : exercise 3 and 4 if someone has developed these programs then please post it here... check the programs posted by me and anubhav for its correctness to the question in lab manual if u find something wrong please let us know... also start concentrating on other parts of lab course like UNIX and DBMS and Dat a sructures... till then learn java... santanu December 22, 2006 07:46 am This is intended for 0903, which I got from some website. But not sure "calendar of a given date" would be this program. But this can probably be modified. QUOTE import java.applet.*; import java.awt.*; import java.util.*; public class calendar extends Applet { Graphics screenG;

Dimension dimension; Choice month; TextField year; Button previous; Button next; Date today; int thisMonth; int thisYear; int selectedMonth; int selectedYear; int colWidth; int rowHeight; int monthDays [] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int leapDays [] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; FontMetrics metrics; public {  //  //  // static void main (String args[]) This main is not used when this program is invoked as an applet, but the code here allows this program to run as either a standalone java program or as an applet. f1; c1;

 Frame  calendar

 c1 = new calendar();  c1.setLayout (new FlowLayout());     f1 = new Frame ("Perpetual Calendar"); f1.resize (375, 350); f1.add ("Center", c1); f1.show();

 c1.init();  c1.start();  c1.getLayout().layoutContainer (c1); } public String getAppletInfo () {  return ("Calendar Applet"); } public boolean leapYear (int year) {  if ((year % 400) == 0)  return (true);  if ((year > 1582) && ((year % 100) == 0))  return (false);  if ((year % 4) == 0)  return (true);  return (false); } public void drawMonth (int startDay, int nDays, boolean special) {  int i;

    Â

int col = startDay + 1; int row = 2; int x; int y; String s;

 for (i = 1; i <= nDays; i++)  {  if (special && (i == 5))   i += 10; // skip 10 days (Oct 5-14) in October, 1582     s = "" + i; x = col * colWidth - metrics.stringWidth (s); y = row * rowHeight; screenG.drawString (s, x, y);

 col++;  if (col > 7)  {   col = 1;   row++;  }  } } public void doMonth (int month, int year) {  boolean leap = leapYear (year);  int daysInMonth;  int startOfMonth;  int y = year - 1;  int i;  boolean special = ((year == 1582) && (month == 9));  boolean pre = ((year < 1582) || ((year == 1582) && (month <= 9)));  if (pre)  startOfMonth = 6 + y + (y / 4);  else  startOfMonth = 1 + y + (y / 4) - (y / 100) + (y / 400);             if (leap) { daysInMonth = leapDays [month]; for (i = 0; i < month; i++)  startOfMonth += leapDays [i]; } else { daysInMonth = monthDays [month]; for (i = 0; i < month; i++)  startOfMonth += monthDays [i]; }

 drawMonth (startOfMonth % 7, daysInMonth, special); } public int parseYear (String y) {

        }

if ((y.length () == 4) Â && (y.charAt(0) >= '0') && (y.charAt(0) Â && (y.charAt(1) >= '0') && (y.charAt(1) Â && (y.charAt(2) >= '0') && (y.charAt(2) Â && (y.charAt(3) >= '0') && (y.charAt(3) return (Integer.parseInt (y)); else return (-1);

<= <= <= <=

'9') '9') '9') '9'))

public void init () { Â dimension = size (); Â colWidth = dimension.width / 8; Â rowHeight = dimension.height / 7; Â today = new Date (); Â thisMonth = today.getMonth (); Â thisYear = today.getYear () + 1900; Â selectedMonth = thisMonth; Â selectedYear = thisYear; Â previous = new Button ("Previous Month"); Â add (previous); Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â month = new Choice (); month.addItem ("January"); month.addItem ("February"); month.addItem ("March"); month.addItem ("April"); month.addItem ("May"); month.addItem ("June"); month.addItem ("July"); month.addItem ("August"); month.addItem ("September"); month.addItem ("October"); month.addItem ("November"); month.addItem ("December"); month.select (thisMonth); add (month);

 year = new TextField ("" + thisYear, 4);  add (year);  next = new Button ("Next Month");  add (next);  screenG = getGraphics ();  metrics = screenG.getFontMetrics (); } public void paint (Graphics g) {  if (screenG != null)  {  // the following three lines are workarounds for NetScape 2.0 bugs.  Point p = month.location ();  g.clearRect (0, 0, dimension.width, dimension.height);  month.move (p.x, (p.y & -2) + (selectedMonth & 1));

 doMonth (selectedMonth, selectedYear);  } } public void setYear (int y) {  if (y > 999)  year.setText ("" + y);  else if (y > 99)  year.setText ("0" + y);  else if (y > 9)  year.setText ("00" + y);  else  year.setText ("000" + y); } public boolean action (Event e, Object o) {  if (e.target == previous)  {  if ((selectedYear > 1) || (selectedMonth > 0))  {   selectedMonth--;   if (selectedMonth < 0)   {   selectedMonth = 11;   selectedYear--;   }   month.select (selectedMonth);   setYear (selectedYear);   repaint ();  }  return (true);  }           if (e.target == next) { if ((selectedYear < 9999) || (selectedMonth < 11)) {  selectedMonth++;  if (selectedMonth > 11)  {  selectedMonth = 0;  selectedYear++;  }

  month.select (selectedMonth);   setYear (selectedYear);   repaint ();  }  return (true);  }  if (e.target == month)  {  int m = month.getSelectedIndex ();

Â

setYear (selectedYear);

 if (m != selectedMonth)  {   selectedMonth = month.getSelectedIndex ();   repaint ();  }  return (true);  }  if (e.target == year)  {  int y = parseYear (year.getText ());  if ((y > 0) && (y != selectedYear))  {   selectedYear = y;   repaint ();  }  return (true);  }  return (false); } public boolean handleEvent (Event e) {  if (e.target == year)  {  int y = parseYear (year.getText ());  if ((y > 0) && (y != selectedYear))  {   selectedYear = y;   repaint ();  }  }  return super.handleEvent (e); } } This gives a warning but makes a class file alright. Use the following tag to ca ll from a browserQUOTE <html> <body> <APPLET CODE="calendar" width=700 height=550></applet> </body> </html>

santanu December 22, 2006 08:03 am For 1004, we probably have to create an ODBC driver for MS Access using Control Panel -> A dministrative Tools -> Data Sources (ODBC) , if its not already there. Then we have to use the following connection strings in the program. I'm working on the program. QUOTE Â Â private static final String accessDBURLPrefix = "jdbc:odbc:Driver={Microsoft A ccess Driver (*.mdb)};DBQ="; Â Â private static final String accessDBURLSuffix = ";DriverID=22;READONLY=false}" ; Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â // Initialize the JdbcOdbc Bridge Driver static { Â Â try { Â Â Â Â Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Â Â } catch(ClassNotFoundException e) { Â Â Â Â System.err.println("JdbcOdbc Bridge Driver not found!"); Â Â } } /** Creates a Connection to a Access Database */ public static Connection getAccessDBConnection(String filename) throws SQLExce { Â Â filename = filename.replace('', '/').trim(); Â Â String databaseURL = accessDBURLPrefix + filename + accessDBURLSuffix; Â Â return DriverManager.getConnection(databaseURL, "", ""); }Â

    ption         OR QUOTE                     Â

 private Connection conDatabase;  private Statement qryDatabase;  private ResultSet rsDatabase;                 //open connection to database /* set up DriverManager to let it know we want to communicate with  ODBC data sources. Calling the static forName() method of the Class class*/  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");   // set this to connection string to the database  sURL = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="; sURL += getConnectionData().trim() + ";DriverID=22;READONLY=true}";  System.out.println("url: "+sURL);  // create connection to database using connection string conDatabase = DriverManager.getConnection(sURL, "", "");   // setup java.sql.Statement to run queries

  qryDatabase = conDatabase.createStatement(); Here's a sample prog QUOTE import java.sql.*; import java.util.*; public class ListOfRegisteredDrivers { /** Creates a new instance of ListOfRegisteredDrivers */ public static void main(String s[]) { //ResultSet rs; Statement stmt; Connection con=null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException e) { System.out.println(e); } try { con = DriverManager.getConnection("jdbc:odbc:mydb"); stmt = con.createStatement(); String s1 = "insert into student values(111,'amit')"; stmt.executeUpdate(s1); } catch(SQLException e) { System.out.println(e); } finally { try { con.close(); } catch(SQLException e) { System.out.println(e); } } } } There's a zipped pdf file (about 201KB) containing a great tutorial explaining t he whole process.

santanu December 25, 2006 11:15 pm S5.2 The logic for the train is not perfectly ok. But the main purpose of this p rogram is generating user defined exception, which the following program takes c are of. I left out the direction parameter in the exception messege. U can inclu de that. QUOTE class Vehicle { char direction; int speed; Vehicle (char dir,int spd) { direction = dir; speed = spd; } }; class CollisionException extends Exception { private int v1Dir,v1Speed,v2Dir,v2Speed; CollisionException (char a,int b,char c,int d) { v1Dir=a; v1Speed=b; v2Dir=c; v2Speed=d; } public String toString() { return("Beware ! There is a chance of Collision [for v1="+v1Dir+","+v1Speed+" and "+"for v2="+v2Dir+","+v2Speed+"]"); } } class q0502 { public static void main(String[] args) throws CollisionException { int flag=0; System.out.println("It is assumed that vehicle v1 departs earlier than v2"); Vehicle v1 = new Vehicle('N',80); Vehicle v2 = new Vehicle('N',110); try { if (((v1.direction == v2.direction)&&(v1.speed < v2.speed))||(v1.direction != v2.direction)) { throw new CollisionException(v1.direction,v1.speed,v2.direction,v2.speed); } System.out.println("All Systems OK"); } catch(CollisionException c) {

System.out.println("CollisionException caught:"+c); } } } ajeet January 05, 2007 10:44 pm Does any know in session6 q2 how can we check whether the command line argument is non-integer or not. Also in session 10 Q1 it is throwing error and not compling. santanu January 05, 2007 11:16 pm Actually command line argument is always non-integer even if we enter a digit. T hat's why (String args[]) is used. We have to use parseInt to convert numerical arguments to integer - java.lang.Integer.parseInt(String) . Now what if the argument is not numerical? You can use the following to check th e argument's nature public static boolean isDigit(char ch) =>Determines if the specified character i s a digit. or you can use CODE int firstArg; if (args.length > 0) { Â Â try { Â Â Â Â firstArg = Integer.parseInt(args[0]); Â Â } catch (NumberFormatException e) { Â Â Â Â System.err.println("Argument must be an integer"); Â Â Â Â System.exit(1); Â Â } } QUOTE Also in session 10 Q1 it is throwing error and not compling. It compiled alright in my case and I got the output QUOTE ------------ Run ---------www.ignou.ac.in/220.227.168.115 www.indiatimes.com/203.199.74.11 www.rediff.com/203.199.74.8 www.santanu.in/216.240.157.220 localhost/127.0.0.1 Output completed (4 sec consumed) - Normal Termination It compiles offline but u have to run it online so that it can access the DNS se rver and get the IP address. khushvadan November 30, 2007 12:53 pm QUOTE (santanu @ 5 Jan 2007, 11:16 PM)

Actually command line argument is always non-integer even if we enter a digit. T hat's why (String args[]) is used. We have to use parseInt to convert numerical arguments to integer - java.lang.Integer.parseInt(String) . Now what if the argument is not numerical? You can use the following to check th e argument's nature public static boolean isDigit(char ch) =>Determines if the specified character i s a digit. or you can use CODE int firstArg; if (args.length > 0) { Â Â try { Â Â Â Â firstArg = Integer.parseInt(args[0]); Â Â } catch (NumberFormatException e) { Â Â Â Â System.err.println("Argument must be an integer"); Â Â Â Â System.exit(1); Â Â } }

It compiled alright in my case and I got the output -

It compiles offline but u have to run it online so that it can access the DNS se rver and get the IP address. Hi to all Here i am posting a solved Java Lab Manual which is useful to you all. Thanks..... khushvadan November 30, 2007 01:04 pm Hi to all Here i am posting a solved Java Lab Manual which is useful to you all. Thanks..... Anubhav January 01, 2008 03:06 am how to open the .rar file I am using windows compressed files. vaby January 01, 2008 12:48 pm QUOTE (Anubhav @ 1 Jan 2008, 03:06 AM) how to open the .rar file I am using windows compressed files. you will need WinRar software - its similar to WinZip - but compression is much more better.... here is the link for downloadning the sofware http://www.rarlab.com/rar/wrar371.exe its small in size approx 1.2mb-2.mb minakshibaul January 02, 2008 11:17 pm

Can anybody tell me about the swapping of two file. It is in the June 2007 Practical question. I did it but it can not be swapping. Please mark out the errors: // Swap contents of two files import java.io.*; class june07_3_swap_file { public static void main(String ar[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String f1,f2,f3; int i; try { System.out.print("Enter 1st file name: "); f1=br.readLine(); System.out.print("Enter 2nd file name: "); f2=br.readLine(); //Contents of each file System.out.println("Content of " + f1 + "--->\n"); FileReader fr=new FileReader(f1); i=fr.read(); while(i!=-1) { System.out.print((char)i); i=fr.read(); } fr.close(); System.out.println("\nContent of " + f2 + "--->\n"); fr=new FileReader(f2); i=fr.read(); while(i!=-1) { System.out.print((char)i); i=fr.read(); } fr.close(); // Copy the contents from file1 to temp fr=new FileReader(f1); FileWriter fw=new FileWriter("temp.txt"); i=fr.read(); while(i!=-1) { fw.write(i); i=fr.read(); } fr.delete(); fr.close(); fw.close(); //copy the contents from file2 to file1 fr=new FileReader(f2); fw=new FileWriter(f1); i=fr.read(); while(i!=-1) { fw.write(i); i=fr.read(); }

fr.close(); fw.close(); //copy the contents from temp to file1 fr=new FileReader("temp.txt"); fw=new FileWriter(f1); i=fr.read(); while(i!=-1) { fw.write(i); i=fr.read(); } fr.close(); fw.close(); System.out.println("After swapping\n"); //Contents of each file System.out.println("Content of " + f1 + "--->\n"); fr=new FileReader(f1); i=fr.read(); while(i!=-1) { System.out.print((char)i); i=fr.read(); } fr.close(); System.out.println("\nContent of " + f2 + "--->\n"); fr=new FileReader(f2); i=fr.read(); while(i!=-1) { System.out.print((char)i); i=fr.read(); } fr.close(); } catch(Exception e){ } } }[B] tusharks July 06, 2008 10:07 am Assignment Solution for Session 1: S101 class Area1 { int ht,wt; int ar; Area1(int x,int y) { ht=x; wt=y; } void area1() { ar=ht*wt; System.out.println("Area of a rectangle = " + ar);

} } class S11 { public static void main(String args[]) { Area1 a1=new Area1(10,20); a1.area1(); } } S102 class S12 { public static void main(String arg[]) { Calc calc=new Calc(); calc.c1(); } } class Calc { int a,b; Calc() { a=10; b=5; } void c1() { int temp; temp = (a<<2) + (b>>2); System.out.println("1. : " + temp); temp = (a)|(b>>0); System.out.println("1. : " + temp); temp = (a+b*100)/10; System.out.println("3. : " + temp); temp = a&b; System.out.println("4. : " + temp); } } S103 class S13 { public static void main(String args[]) { int i=1; while(true) { i+=2; if(i==100)

{ System.out.println("Break is encountered at i = " + i); break; } if(i==99) { System.out.println("Continue is encountered at i = " + i); i=2; continue; } } } } S104 class S14 { public static void main(String args[]) { float avg,total=0; int i; for(i=0;i<args.length;i++) { total+=Float.parseFloat(args[i]); } avg=total/args.length; System.out.println("\nNo of subjects in 10+2 : " + args.length); System.out.println("\nTotal marks in 10+2 : " + total); System.out.println("\nAverage in 10+2 : " + avg); } } divsj October 12, 2009 10:23 pm Hi friends am providing some lab manual solutions here hope it will help u to prepare the records http://www.4shared.com/file/140370916/8cc9...LAB_RECORD.html regards div sancad November 14, 2009 07:57 pm hi buddies, Can anybody help me to debugg the following code for reversing integer array using recursion?? public class Array { public static void main(String args[]) { int[] Arr = {21,22,23,24,25,26,27,28,29}; int a1[]= new int Arr[]; int i=0; int n=a1.length; a1.prnt(i,n);

a1.reverse(i,n); System.out.println("Array in reverse order"); a1.prnt(i,n); } void prnt(int i, int n) { for(i = 0; i < n; i++) { System.out.print(a1[i] + " "); } } void reverse(int i, int n) { int temp =a1[i]; a1[i]=a1[n-i-1]; a1[n-i-1]=temp; while (i<n/2) reverse(++i,n); } } anzerp May 06, 2012 09:56 pm Java labrecord corrected http://www.4shared.com/office/5cJl_CY6/java_lab.html Pages: 1, 2 This is a "lo-fi" version of our main content. To view the full version with mor e information, formatting and images, please click here . IGNOU MCA Students Forum (IMSF) ©2008 Santanu Acharya Invision Power Board © 2001-2013 Invision Power Services, Inc. Adapted by Shaun Harrison Translated and modified by Fantome et David, Lafter

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close