+ All Categories
Home > Documents > Java Lab Programs

Java Lab Programs

Date post: 19-Dec-2015
Category:
Upload: adhi
View: 419 times
Download: 8 times
Share this document with a friend
Description:
java
53
1a. Implement linear search : using recursion. //linear using recurssion import java.util.*; import java.util.Scanner.*; class LinearSearch { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the size of the array: "); int size = input.nextInt(); System.out.print("Enter an array of numbers: "); int[] arr = new int[size]; for(int i=0; i<arr.length; i++) { arr[i]=input.nextInt(); } System.out.print("Enter the number you want to search: "); int search = input.nextInt(); Linear_Search access = new Linear_Search(); System.out.print("The position of the search item is at array index "); access.linSearch2(arr, 0, arr.length, search); } } class Linear_Search { public void linSearch2(int[] arr, int fIndex, int lIndex, int searchNum) { if(fIndex == lIndex) { System.out.print("-1"); } else {
Transcript
Page 1: Java Lab Programs

1a. Implement linear search : using recursion.

//linear using recurssion

import java.util.*;import java.util.Scanner.*;

class LinearSearch{ public static void main(String[] args) { Scanner input = new Scanner(System.in);

System.out.print("Enter the size of the array: "); int size = input.nextInt(); System.out.print("Enter an array of numbers: ");

int[] arr = new int[size];

for(int i=0; i<arr.length; i++) { arr[i]=input.nextInt(); }

System.out.print("Enter the number you want to search: "); int search = input.nextInt();

Linear_Search access = new Linear_Search();

System.out.print("The position of the search item is at array index "); access.linSearch2(arr, 0, arr.length, search); }

}class Linear_Search

{

public void linSearch2(int[] arr, int fIndex, int lIndex, int searchNum)

{

if(fIndex == lIndex)

{

System.out.print("-1");

}

else

{

Page 2: Java Lab Programs

if(arr[fIndex] == searchNum)

{

System.out.print(fIndex);

}

else

{

linSearch2(arr, fIndex+1, lIndex, searchNum);

}

}

}}-----------------------------------------------------------------------

3. Implement linked list showing all the basic operations.

/*

* Java Program to Implement Singly Linked List

*/

import java.util.Scanner;

/* Class Node */

class Node

{

protected int data;

protected Node link;

/* Constructor */

public Node()

{

link = null;

data = 0;

Page 3: Java Lab Programs

}

/* Constructor */

public Node(int d,Node n)

{

data = d;

link = n;

}

/* Function to set link to next Node */

public void setLink(Node n)

{

link = n;

}

/* Function to set data to current Node */

public void setData(int d) {

data = d;

}

/* Function to get link to next node */

public Node getLink()

{

return link;

}

/* Function to get data from current Node */

public int getData()

{

return data;

}

}

Page 4: Java Lab Programs

/* Class linkedList */

class linkedList

{

protected Node start;

protected Node end ;

public int size ;

/* Constructor */

public linkedList()

{

start = null;

end = null;

size = 0;

}

/* Function to check if list is empty */

public boolean isEmpty()

{

return start == null;

}

/* Function to get size of list */

public int getSize() {

return size;

}

/* Function to insert an element at begining */

public void insertAtStart(int val)

{

Node nptr = new Node(val, null);

size++ ;

if(start == null)

Page 5: Java Lab Programs

{

start = nptr;

end = start;

}

else

{

nptr.setLink(start);

start = nptr;

}

}

/* Function to insert an element at end */

public void insertAtEnd(int val)

{

Node nptr = new Node(val,null);

size++ ;

if(start == null)

{

start = nptr;

end = start;

}

else

{

end.setLink(nptr);

end = nptr;

}

}

/* Function to insert an element at position */ public void insertAtPos(int val , int pos)

{

Page 6: Java Lab Programs

Node nptr = new Node(val, null);

Node ptr = start;

pos = pos - 1 ;

for (int i = 1; i < size; i++)

{

if (i == pos)

{

Node tmp = ptr.getLink() ;

ptr.setLink(nptr);

nptr.setLink(tmp);

break;

}

ptr = ptr.getLink();

}

size++ ;

}

/* Function to delete an element at position */

public void deleteAtPos(int pos)

{

if (pos == 1)

{

start = start.getLink();

size--;

return ;

}

if (pos == size)

{

Node s = start;

Node t = start;

Page 7: Java Lab Programs

while (s != end)

{

t = s;

s = s.getLink();

} end = t;

end.setLink(null);

size --;

return;

}

Node ptr = start;

pos = pos - 1 ;

for (int i = 1; i < size - 1; i++)

{

if (i == pos)

{

Node tmp = ptr.getLink();

tmp = tmp.getLink();

ptr.setLink(tmp);

break;

}

ptr = ptr.getLink();

}

size-- ;

}

/* Function to display elements */

public void display()

{

System.out.print("\nSingly Linked List = ");

if (size == 0)

Page 8: Java Lab Programs

{

System.out.print("empty\n");

return;

}

if (start.getLink() == null)

{

System.out.println(start.getData() );

return;

}

Node ptr = start;

System.out.print(start.getData()+ "->");

ptr = start.getLink(); while (ptr.getLink() != null)

{

System.out.print(ptr.getData()+ "->");

ptr = ptr.getLink();

}

System.out.print(ptr.getData()+ "\n");

}

}

/* Class SinglyLinkedList */

public class SinglyLinkedList

{

public static void main(String[] args)

{

Scanner scan = new Scanner(System.in);

/* Creating object of class linkedList */

linkedList list = new linkedList();

Page 9: Java Lab Programs

System.out.println("Singly Linked List Test\n");

char ch;

/* Perform list operations */

do

{

System.out.println("\nSingly Linked List Operations\n");

System.out.println("1. insert at begining");

System.out.println("2. insert at end");

System.out.println("3. insert at position");

System.out.println("4. delete at position");

System.out.println("5. check empty");

System.out.println("6. get size");

int choice = scan.nextInt();

switch (choice)

{

case 1 : System.out.println("Enter integer element to insert");

list.insertAtStart( scan.nextInt() );

break;

case 2 :

System.out.println("Enter integer element to insert");

list.insertAtEnd( scan.nextInt() );

break;

case 3 :

System.out.println("Enter integer element to insert");

int num = scan.nextInt() ;

System.out.println("Enter position");

int pos = scan.nextInt() ;

if (pos <= 1 || pos > list.getSize() )

System.out.println("Invalid position\n");

Page 10: Java Lab Programs

else

list.insertAtPos(num, pos);

break;

case 4 :

System.out.println("Enter position");

int p = scan.nextInt() ;

if (p < 1 || p > list.getSize() )

System.out.println("Invalid position\n");

else

list.deleteAtPos(p);

break;

case 5 : System.out.println("Empty status = "+ list.isEmpty());

break;

case 6 :

System.out.println("Size = "+ list.getSize() +" \n");

break;

default :

System.out.println("Wrong Entry \n ");

break;

}

/* Display List */

list.display();

System.out.println("\nDo you want to continue (Type y or n) \n");

ch = scan.next().charAt(0);

} while (ch == 'Y'|| ch == 'y');

}

}

Page 11: Java Lab Programs

-----------------------------------------------------------------------

4. Implement doubly linked list showing all the basic operations.

/*

* Java Program to Implement Doubly Linked List

*/

import java.util.Scanner.*;

/* Class Node */

class Node

{

protected int data;

protected Node next, prev;

/* Constructor */

public Node()

{

next = null;

prev = null;

data = 0;

}

/* Constructor */

public Node(int d, Node n, Node p)

{

data = d;

next = n;

prev = p;

}

Page 12: Java Lab Programs

/* Function to set link to next node */

public void setLinkNext(Node n)

{

next = n;

}

/* Function to set link to previous node */

public void setLinkPrev(Node p)

{

prev = p; }

/* Funtion to get link to next node */

public Node getLinkNext()

{

return next;

}

/* Function to get link to previous node */

public Node getLinkPrev()

{

return prev;

}

/* Function to set data to node */

public void setData(int d)

{

data = d;

}

/* Function to get data from node */

public int getData()

{

return data;

}

Page 13: Java Lab Programs

}

/* Class linkedList */

class linkedList

{

protected Node start;

protected Node end ;

public int size;

/* Constructor */

public linkedList()

{

start = null; end = null;

size = 0;

}

/* Function to check if list is empty */

public boolean isEmpty()

{

return start == null;

}

/* Function to get size of list */

public int getSize()

{

return size;

}

/* Function to insert element at begining */

public void insertAtStart(int val)

{

Page 14: Java Lab Programs

Node nptr = new Node(val, null, null);

if(start == null)

{

start = nptr;

end = start;

}

else

{

start.setLinkPrev(nptr);

nptr.setLinkNext(start);

start = nptr;

}

size++;

}

/* Function to insert element at end */

public void insertAtEnd(int val)

{

Node nptr = new Node(val, null, null);

if(start == null)

{

start = nptr; end = start;

}

else

{

nptr.setLinkPrev(end);

end.setLinkNext(nptr);

end = nptr;

}

size++;

Page 15: Java Lab Programs

}

/* Function to insert element at position */

public void insertAtPos(int val , int pos)

{

Node nptr = new Node(val, null, null);

if (pos == 1)

{

insertAtStart(val);

return;

}

Node ptr = start;

for (int i = 2; i <= size; i++)

{

if (i == pos)

{

Node tmp = ptr.getLinkNext();

ptr.setLinkNext(nptr);

nptr.setLinkPrev(ptr);

nptr.setLinkNext(tmp);

tmp.setLinkPrev(nptr); }

ptr = ptr.getLinkNext();

}

size++ ;

}

/* Function to delete node at position */

public void deleteAtPos(int pos)

{

if (pos == 1)

Page 16: Java Lab Programs

{

if (size == 1)

{

start = null;

end = null;

size = 0;

return;

}

start = start.getLinkNext();

start.setLinkPrev(null);

size--;

return ;

}

if (pos == size)

{

end = end.getLinkPrev();

end.setLinkNext(null);

size-- ;

}

Node ptr = start.getLinkNext();

for (int i = 2; i <= size; i++)

{

if (i == pos)

{

Node p = ptr.getLinkPrev();

Node n = ptr.getLinkNext(); p.setLinkNext(n);

n.setLinkPrev(p);

size-- ;

return;

Page 17: Java Lab Programs

}

ptr = ptr.getLinkNext();

}

}

/* Function to display status of list */

public void display()

{

System.out.print("\nDoubly Linked List = ");

if (size == 0)

{

System.out.print("empty\n");

return;

}

if (start.getLinkNext() == null)

{

System.out.println(start.getData() );

return;

}

Node ptr = start;

System.out.print(start.getData()+ " <-> ");

ptr = start.getLinkNext();

while (ptr.getLinkNext() != null)

{

System.out.print(ptr.getData()+ " <-> ");

ptr = ptr.getLinkNext();

}

System.out.print(ptr.getData()+ "\n");

}

}

Page 18: Java Lab Programs

/* Class DoublyLinkedList */

public class DoublyLinkedList

{

public static void main(String[] args)

{

Scanner scan = new Scanner(System.in);

/* Creating object of linkedList */

linkedList list = new linkedList();

System.out.println("Doubly Linked List Test\n");

char ch;

/* Perform list operations */

do

{

System.out.println("\nDoubly Linked List Operations\n");

System.out.println("1. insert at begining");

System.out.println("2. insert at end");

System.out.println("3. insert at position");

System.out.println("4. delete at position");

System.out.println("5. check empty");

System.out.println("6. get size");

int choice = scan.nextInt();

switch (choice)

{

case 1 :

System.out.println("Enter integer element to insert");

list.insertAtStart( scan.nextInt() );

break;

case 2 :

Page 19: Java Lab Programs

System.out.println("Enter integer element to insert");

list.insertAtEnd( scan.nextInt() );

break;

case 3 :

System.out.println("Enter integer element to insert");

int num = scan.nextInt() ; System.out.println("Enter position");

int pos = scan.nextInt() ;

if (pos < 1 || pos > list.getSize() )

System.out.println("Invalid position\n");

else

list.insertAtPos(num, pos);

break;

case 4 :

System.out.println("Enter position");

int p = scan.nextInt() ;

if (p < 1 || p > list.getSize() )

System.out.println("Invalid position\n");

else

list.deleteAtPos(p);

break;

case 5 :

System.out.println("Empty status = "+ list.isEmpty());

break;

case 6 :

System.out.println("Size = "+ list.getSize() +" \n");

break;

default :

System.out.println("Wrong Entry \n ");

break;

Page 20: Java Lab Programs

}

/* Display List */

list.display();

System.out.println("\nDo you want to continue (Type y or n) \n");

ch = scan.next().charAt(0);

} while (ch == 'Y'|| ch == 'y');

}

}

-----------------------------------------------------------------------

7. Implement priority queue showing all the basic operations.

/**

** Java Program to implement Priority Queue

**/

import java.util.Scanner;

/** class Task **/

class Task

{

String job;

int priority;

/** Constructor **/

public Task(String job, int priority)

{

this.job = job;

Page 21: Java Lab Programs

this.priority = priority;

}

/** toString() **/

public String toString()

{ return "Job Name : "+ job +"\nPriority : "+ priority;

}

}

/** Class PriorityQueue **/

class PriorityQueue

{

private Task[] heap;

private int heapSize, capacity;

/** Constructor **/

public PriorityQueue(int capacity)

{

this.capacity = capacity + 1;

heap = new Task[this.capacity];

heapSize = 0;

}

/** function to clear **/

public void clear()

{

heap = new Task[capacity];

heapSize = 0;

}

/** function to check if empty **/

Page 22: Java Lab Programs

public boolean isEmpty()

{

return heapSize == 0;

}

/** function to check if full **/

public boolean isFull()

{

return heapSize == capacity - 1;

}

/** function to get Size **/

public int size()

{ return heapSize;

}

/** function to insert task **/

public void insert(String job, int priority)

{

Task newJob = new Task(job, priority);

heap[++heapSize] = newJob;

int pos = heapSize;

while (pos != 1 && newJob.priority > heap[pos/2].priority)

{

heap[pos] = heap[pos/2];

pos /=2;

}

heap[pos] = newJob;

}

/** function to remove task **/

public Task remove()

Page 23: Java Lab Programs

{

int parent, child;

Task item, temp;

if (isEmpty() )

{

System.out.println("Heap is empty");

return null;

}

item = heap[1];

temp = heap[heapSize--];

parent = 1;

child = 2;

while (child <= heapSize)

{ if (child < heapSize && heap[child].priority < heap[child + 1].priority)

child++;

if (temp.priority >= heap[child].priority)

break;

heap[parent] = heap[child];

parent = child;

child *= 2;

}

heap[parent] = temp;

return item;

}

Page 24: Java Lab Programs

}

/** Class PriorityQueueTest **/

public class PriorityQueueTest

{

public static void main(String[] args)

{

Scanner scan = new Scanner(System.in);

System.out.println("Priority Queue Test\n");

System.out.println("Enter size of priority queue ");

PriorityQueue pq = new PriorityQueue(scan.nextInt() );

char ch;

/* Perform Priority Queue operations */

do

{

System.out.println("\nPriority Queue Operations\n");

System.out.println("1. insert");

System.out.println("2. remove");

System.out.println("3. check empty");

System.out.println("4. check full");

System.out.println("5. clear"); System.out.println("6. size");

int choice = scan.nextInt();

switch (choice)

{

case 1 :

Page 25: Java Lab Programs

System.out.println("Enter job name and priority");

pq.insert(scan.next(), scan.nextInt() );

break;

case 2 :

System.out.println("\nJob removed \n\n"+ pq.remove());

break;

case 3 :

System.out.println("\nEmpty Status : "+ pq.isEmpty() );

break;

case 4 :

System.out.println("\nFull Status : "+ pq.isFull() );

break;

case 5 :

System.out.println("\nPriority Queue Cleared");

pq.clear();

break;

case 6 :

System.out.println("\nSize = "+ pq.size() );

break;

default :

System.out.println("Wrong Entry \n ");

break;

}

System.out.println("\nDo you want to continue (Type y or n) \n");

ch = scan.next().charAt(0);

} while (ch == 'Y'|| ch == 'y');

}

}

Page 26: Java Lab Programs

/*output:

Priority Queue Test Enter size of priority queue7 Priority Queue Operations 1. insert2. remove3. check empty4. check full5. clear6. size1Enter job name and priorityjob1 24 Do you want to continue (Type y or n) y Priority Queue Operations 1. insert2. remove3. check empty4. check full5. clear6. size

*/

--------------------------------------------------------------------------------------------------------------------------------------8. Write a program to multiply two matrices using multithreading.

import java.lang.*;import java.io.*;class MatMulti extends Thread{ static int in1[][]; static int in2[][]; static int out[][]; static int n=2; int row; MatMulti(int i) { row=i;

Page 27: Java Lab Programs

this.start(); } public void run() { int i,j; for(i=0;i<n;i++) { out[row][i]=0; for(j=0;j<n;j++) out[row][i]=out[row][i]+in1[row][j]*in2[j][i]; } } public static void main(String args[]) { int i,j; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter the order of Matrix : "); try { n=Integer.parseInt(br.readLine()); }catch(Exception e){} in1=new int[n][n]; in2=new int[n][n]; out=new int[n][n]; System.out.println("Enter the First Matrix : "); for(i=0;i<n;i++) { for(j=0;j<n;j++) { try { in1[i][j]=Integer.parseInt(br.readLine()); }catch(Exception e){} } } System.out.println("Enter the Second Matrix : "); for(i=0;i<n;i++) { for(j=0;j<n;j++) { try { in2[i][j]=Integer.parseInt(br.readLine()); }catch(Exception e){} } } MatMulti mat[]=new MatMulti[n]; for(i=0;i<n;i++) mat[i]=new MatMulti(i); try { for(i=0;i<n;i++) mat[i].join(); }catch(Exception e){}

Page 28: Java Lab Programs

System.out.println("OUTPUT :"); for(i=0;i<n;i++) for(j=0;j<n;j++) System.out.println(out[i][j]); }}

-----------------------------------------------------------------------

9. Implement an abstract class named Person and two subclasses named Student and Employee. A person has a name, address, phone number and e-mail address. A student has a class status (freshman, second year junior or senior). Define the status as a constant. An employee has an office, salary and date-hired. Implement the above classes. Provide Constructors for classes to initialize private variables. Override the toString method in each class to display the class name and the persons name. Write an application to create objects of type Student and Employee and print the persons name -and the class name of the objects.

abstract class person

{

protected String na;

protected int ID;

person(String name,int id)

{

na=name;

ID=id;

}

abstract public void tooString();

}

class Student extends person

{

private String curst;

Student(String name1,int id1,int status)

{

super(name1,id1);

Page 29: Java Lab Programs

if(status==1)

{

curst="Freshman";

}

else if(status==2)

{

curst="Second Year";

}

else

{

curst="Senior";

}

}

public void tooString()

{

System.out.println("The Details are\nName:"+na+"ID:"+ID+"Current Status:"+curst);

}

}

class Employee extends person

{

private String dhire,off;

private int salary;

Employee(String name1,int id1,String doh, String office,int sal)

{

super(name1,id1);

dhire=doh;

off=office;

Page 30: Java Lab Programs

salary=sal;

}

public void tooString()

{

System.out.println("The Details are\nName:"+na+"ID:"+ID+"Date Of hire:"+dhire+"Salary:"+salary+"Office:"+off);

}

}

class Morph

{

public static void main(String v[])

{

Student s=new Student("XYZ",345,3);

Employee e=new Employee("ABC",345,"25/9/14","Bangalore",35000);

s.tooString();

e.tooString();

}

}

---------------------------------------------------------------------------------------------------------------------------------

10. Write a program to show that private member of a super class cannot be accessed from derived classes.

/Java program to show private member of super class

//create a super classclass A{int i;private int j;void setij(int x,int y){

Page 31: Java Lab Programs

i=x;j=y;}}

//sub classclass B extends A{int total;void sum(){total=i+j;}}-----------------------------------------------------------------------

11. Write a program in Java to create a Player class. Inherit the classes Cricket Player, Football Player and Hockey Player from Player class.

class Player{String name;int age;Player(String n,int a){name=n; age=a;}void show(){System.out.println("\n");System.out.println("Player name : "+name);System.out.println("Age: "+age);}}class CricketPlayer extends Player{String type;CricketPlayer(String n,String t,int a){super(n,a);type=t;}public void show(){super.show();System.out.println("Player type : "+type);}}class FootballPlayer extends Player{String type;FootballPlayer(String n,String t,int a){super(n,a);type=t;}public void show(){super.show();System.out.println("Player type : "+type);}}class HockeyPlayer extends Player{String type;HockeyPlayer(String n,String t,int a){super(n,a);

Page 32: Java Lab Programs

type=t;}public void show(){super.show();System.out.println("Player type : "+type);}}class TestPlayer{public static void main(String args[]){CricketPlayer c=new CricketPlayer("A","Cricket",25);FootballPlayer f=new FootballPlayer("B","Football",25);HockeyPlayer h=new HockeyPlayer("C","Hockey",25);c.show();f.show();h.show();}}

-----------------------------------------------------------------------

12. Write a class Worker and derive classes DailyWorker and SalariedWorker from it. Every worker has a name and a salary rate. Write method ComPay (int hours) to compute the week pay of every worker. A Daily Worker is paid on the basis of the number of days she/he works. The Salaried Worker gets paid the wage for 40 hours a week no matter what the actual hours are. Test this program to calculate the pay of workers. You are expected to use the concept of polymorphism to write this program.

class Worker{String name;int empno;Worker(int no,String n){empno=no; name=n;}void show(){System.out.println("Employee number : "+empno);System.out.println("Employee name: "+name);}}class DailyWorker extends Worker{int rate;DailyWorker(int no,String n,int r){super(no,n);rate=r;}void company(int h){show();System.out.println("Salary : "+(rate*h));}}class SalariedWorker extends Worker{int rate;SalariedWorker(int no,String n,int r){super(no,n);rate=r;}int hour=40;void company(){

Page 33: Java Lab Programs

show();System.out.println("Salary : "+(rate*hour));}}class TestWorker{public static void main(String args[]){DailyWorker d=new DailyWorker(11,"A",75);SalariedWorker s=new SalariedWorker(22,"B",100);d.company(45);s.company();}}-----------------------------------------------------------------------

13. Consider the trunk calls of a telephone exchange. A trunk call can be ordinary, urgent or lightning. The charges depend on the duration and the type of the call. Writ a program using the concept of polymorphism in Java to calculate the charges.

import java.util.*;class Calls{float dur;String type;float rate(){if(type.equals("urgent"))return 4.5f;else if(type=="lightning")return 3.5f;elsereturn 3f;}}class Bill extends Calls{float amount;void read(){Scanner input=new Scanner(System.in);System.out.print("Enter Call Type(urgent,lightning,ordinary): ");type=input.next();System.out.print("Enter Call duration:");dur=input.nextFloat();}void calculate(){if(dur<=1.5){amount=rate()*dur+1.5f;}else if(dur<=3){amount=rate()*dur+2.5f;}else if(dur<=5){amount=rate()*dur+4.5f;}else{amount=rate()*dur+5f;}}void print(){System.out.println(" Call Type : "+type);System.out.println(" Duration : "+dur);System.out.println(" Charge: "+amount);

Page 34: Java Lab Programs

}}class TelephoneExchange{public static void main(String arg[]){String x="yes";Scanner input=new Scanner(System.in);

while(x.equals("yes")||x.equals("Y")){Bill b=new Bill();b.read();b.calculate();b.print();System.out.println("Do you want another transaction? TYPE yes if you want to");input.next();}}}

-----------------------------------------------------------------------

15. Create an Interface having two methods division and modules. Create a class, which overrides these methods.

interface Artth_operations

{

void division(int a,int b);

void modules(int c, int d);

}

class calculate implements Artth_operations

{

int div,mod; char na; void name(char n)

{

na=n;

}

public void division(int a, int b)

{

div=a/b;

}

Page 35: Java Lab Programs

public void modules(int c, int d)

{

mod=c/d;

}

void disp()

{

System.out.println("Division :"+div);

System.out.println("Modules :"+mod);

}

}

class DivisionModulus

{

public static void main(String args[])

{ calculate s=new calculate();

s.division(15, 3);

s.modules(15, 4);

s.disp();

}

}--------------------------------------------------------------

16. Write a program in Java which implements interface Student which has two methods Display Grade and Attendance for PG Students and UG Students (PG Students and UG Students are two different classes for Post Graduate and Under Graduate students respectively).

import java.io.*;

interface student

{

void disp_grade();

void disp_attendance();

Page 36: Java Lab Programs

}

class pg_stud implements student

{

String name,grade;

int reg,m1,m2,m3,att;

void read()throws Exception

{

DataInputStream in= new DataInputStream(System.in);

System.out.println("enter the register no : ");

reg=Integer.parseInt(in.readLine());

System.out.println("enter the name : ");

name=in.readLine();

System.out.println("enter attendance : ");

att=Integer.parseInt(in.readLine());

System.out.println("enter mark1 : ");

m1=Integer.parseInt(in.readLine());

System.out.println("enter mark2 : ");

m2=Integer.parseInt(in.readLine());

System.out.println("enter mark3 : ");

m3=Integer.parseInt(in.readLine());

}

public void disp_grade()

{

int tt=m1+m2+m3;

if(tt>=250) grade="A";

else if(tt>=200) grade="B";

else if(tt>=150) grade="C";

else if(tt>=100) grade="D";

Page 37: Java Lab Programs

else grade="E";

System.out.println("Grade:"+grade);

}

public void disp_attendance()

{

System.out.println("Attendance:"+att);

}

void disp()

{

System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

System.out.println(" MARK LIST OF PG STUDENTS");

System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

System.out.println("Register No :"+reg);

System.out.println("Name:"+name);

System.out.println("Mark1 :"+m1);

System.out.println("Mark2:"+m2);

System.out.println("Mark3 :"+m3);

disp_grade();

disp_attendance();

}

}class ug_stud implements student

{

String name,grade;

int reg,m1,m2,m3,att;

void read()throws Exception

{

DataInputStream in= new DataInputStream(System.in); System.out.println("enter the register no : ");

reg=Integer.parseInt(in.readLine());

Page 38: Java Lab Programs

System.out.println("enter the name : ");

name=in.readLine();

System.out.println("enter attendance : ");

att=Integer.parseInt(in.readLine());

System.out.println("enter mark1 : ");

m1=Integer.parseInt(in.readLine());

System.out.println("enter mark2 : ");

m2=Integer.parseInt(in.readLine());

System.out.println("enter mark3 : ");

m3=Integer.parseInt(in.readLine());

}

public void disp_grade()

{

int tt=m1+m2+m3;

if(tt>=250) grade="A";

else if(tt>=200) grade="B";

else if(tt>=150) grade="C";

else if(tt>=100) grade="D";

else grade="E";

System.out.println("Grade:"+grade);

}

public void disp_attendance()

{

System.out.println("Attendance :"+att);

}

void disp()

{

System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

System.out.println(" MARK LIST OF UG STUDENTS");

Page 39: Java Lab Programs

System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

System.out.println("Register No :"+reg);

System.out.println("Name:"+name);

System.out.println("Mark1 :"+m1);System.out.println("Mark2 :"+m2);

System.out.println("Mark3 :"+m3);

disp_grade();

disp_attendance();

}

}

class StudentInterface

{

public static void main(String args[])throws Exception

{

pg_stud pg=new pg_stud();

pg.read();

pg.disp();

ug_stud ug=new ug_stud();

ug.read();

ug.disp();

}

} -----------------------------------------------------------------------

17. Write a program in Java to display the names and roll numbers of students. Initialize respective array variables for 10 students. Handle ArrayIndexOutOfBoundsExeption, so that any such problem doesnt cause illegal termination of program.

import java.io.*;

class student

{

String name,grade;

Page 40: Java Lab Programs

int reg,m1,m2,m3;

void read()throws Exception

{

DataInputStream in= new DataInputStream(System.in);

System.out.println("enter the register no : ");

reg=Integer.parseInt(in.readLine());

System.out.println("enter the name : ");

name=in.readLine();

System.out.println("enter mark1 : ");

m1=Integer.parseInt(in.readLine());

System.out.println("enter mark2 : ");

m2=Integer.parseInt(in.readLine());

System.out.println("enter mark3: ");

m3=Integer.parseInt(in.readLine());

}

public void disp_grade()

{

int tt=m1+m2+m3;

if(tt>=250)

grade="A";

else if(tt>=200) grade="B";

else if(tt>=150) grade="C";

else if(tt>=100) grade="D";

else grade="E";

System.out.println("Grade :"+grade);

}void disp()

{

System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

System.out.println(" MARK LIST OF STUDENTS ");

Page 41: Java Lab Programs

System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

System.out.println("Register No :"+reg);

System.out.println("Name :"+name);

System.out.println("Mark1 :"+m1);

System.out.println("Mark2 :"+m2);

System.out.println("Mark3 :"+m3);

disp_grade();}

}

class AIOBException

{

public static void main(String ar[])

{

int no=0;

student s=new student();

try

{

DataInputStream in= new DataInputStream(System.in);

System.out.println("enter the number of students : ");no=Integer.parseInt(in.readLine());

for(int i=0;i<no;i++);

s.read();

}catch(ArrayIndexOutOfBoundsException e)

{

System.out.println("the maximum students should be ten\n");no=10;}

catch(Exception e)

{

System.out.println(e);

}

for(int i=0;i<no;i++);

s.disp();

Page 42: Java Lab Programs

}

-----------------------------------------------------------------------

18. Write a program to solve N queens problem. Provide solution applying branch and bound, and backtracking methods. Provide necessary GUI to display the solution.

// not exactly got.. done for 8queens

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

/* implementation of Algorithm 5.1 with a graphical display added */

public class NQueens2 {

private int[] queencol;

private int queencount = -1, numsol = 0;

private int boardsize;

private JButton[][] board;

private JPanel boardpanel;

private JTextArea solnumtext;

private JPanel wholepanel;

private ImageIcon ii = new ImageIcon("crown.gif");

private int sleepAmount;

private int timesCalled = 0;

public Component createComponents(int howmany, int sleepAmount) {

this.sleepAmount = sleepAmount;

wholepanel = new JPanel();

wholepanel.setLayout(new BorderLayout());

boardsize = howmany;

Page 43: Java Lab Programs

boardpanel = new JPanel();

boardpanel.setLayout(new GridLayout(boardsize,boardsize));

board = new JButton[boardsize][boardsize];

for (int i = 0; i < boardsize; i++)

for (int j = 0; j < boardsize; j++) {

board[i][j] = new JButton();

boardpanel.add(board[i][j]);

}

wholepanel.add("Center", boardpanel);

solnumtext = new JTextArea(10,20);

JScrollPane scroller = new JScrollPane(solnumtext);

wholepanel.add("South", scroller);

solnumtext.setEditable(false);

queencol = new int[boardsize];

return wholepanel;

}

private void gotosleep() {

gotosleep(sleepAmount);

}

private void gotosleep(int howlong) {

try {

Thread.sleep(howlong);

}

catch (InterruptedException e) {}

Page 44: Java Lab Programs

}

public void queens(int i) {

int j;

timesCalled++;

if (promising(i)) {

if (i == boardsize-1) {

gotosleep(sleepAmount);

writeBoard();

}

else

for (j = 0; j < boardsize; j++) {

queencol[i+1] = j;

queens(i+1);

}

}

}

private boolean promising(int i)

{

int k;

boolean answer;

k = 0; // Java array subscripts start at 0 answer = true;

while (k < i && answer) {

// check if any queen threatens the one in the ith row

if (queencol[i] == queencol[k] || Math.abs(queencol[i]-queencol[k]) == i-k)

answer = false;

Page 45: Java Lab Programs

k++;

}

return answer;

}

private void writeBoard() {

numsol++;

solnumtext.append("Solution " + numsol + "\n");

for (int i = 0; i < queencol.length; i++)

solnumtext.append("Queen " + (i + 1) + " at column " + (queencol[i] + 1) + "\n");

for (int i = 0; i < boardsize; i++)

for (int j = 0; j < boardsize; j++) {

if (j == queencol[i])

board[i][j].setIcon(ii);

else

board[i][j].setIcon(null);

}

}

public static void main(String[] args) {

NQueens2 nq = new NQueens2();

JFrame nqf;

int howmany;

int sleepAmount = 0;

String laf = UIManager.getSystemLookAndFeelClassName();

Page 46: Java Lab Programs

try {

UIManager.setLookAndFeel(laf);

}

catch (UnsupportedLookAndFeelException exc) {

System.out.println("Unsupported: " + laf);

}

catch (Exception exc) {

System.out.println("Error loading: " + laf);

}

if (args.length == 0)

howmany = 8;

else {

try {

howmany = Integer.parseInt(args[0]);

}

catch (NumberFormatException ne) {

howmany = 4;

}

try {

sleepAmount = Integer.parseInt(args[1]);

}

catch (Exception e) {

}

}

nqf = new JFrame("N Queens " + howmany);

Component contents = nq.createComponents(howmany, sleepAmount);

nqf.getContentPane().add(contents,BorderLayout.CENTER);

nqf.setBackground(Color.white);

Page 47: Java Lab Programs

nqf.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

nqf.setSize(400, 400);

nqf.show();

//nq.addqueen();

nq.queens(-1); // remember array subscripts start at 0

nq.solnumtext.append("Total of " + nq.numsol +

" solutions\n" + "Recursive calls: " +

nq.timesCalled);

}

}

--------------------------------------------------------------------------------------------------------------------------------------

19. Write a Java program to enable the user to handle any chance of divide by zero exception.

public class DivideByzero

{

public static void main(String args[])

{

int b=100,res=0;

int a[]={0,1,2,5,0,25,0,50,0};

for (int i=0;i<9;i++)

{

try

{

res=res+(b/a[i]);

System.out.println(" "+res);

Page 48: Java Lab Programs

} catch (ArithmeticException e)

{

a[i]=1;

}

}

}

}-----------------------------------------------------------------------

20. Create an exception class, which throws an exception if operand is nonnumeric in calculating modules. (Use command line arguments).

public class EXceptionnonnumeric

{

public static void main(String args[])

{

int sum=0;

int invalid=0;

for(int i=0;i<args.length;i++)

{

try

{

sum+=Integer.parseInt(args[i]); }

catch(NumberFormatException e)

{

invalid++;

}

}

System.out.println("Total number of arguments:"+args.length);

System.out.println("Invalid numbers:"+invalid);

System.out.println("Sum:"+sum);

}

Page 49: Java Lab Programs

}

-----------------------------------------------------------------------

21. On a single track two vehicles are running. As vehicles are going in same direction there is no problem. If the vehicles are running in different direction there is a chance of collision. To avoid collisions write a Java program using exception handling. You are free to make necessary assumptions.

import java.io.*;

class collision extends Exception

{

collision(String s)

{

super(s);

}

}

class TwoVehicles

{

public static void main(String ar[])

{

String t1=null,t2=null;

try

{

DataInputStream in= new DataInputStream(System.in);

System.out.println("enter the direction of vehicle1:(left/right):");

t1=in.readLine();

System.out.println("enter the direction of vehicle2:(left/right):");

t2=in.readLine();

if(!t1.equals(t2))

throw new collision("truck2 has to go on "+ t1 +" direction");

}

Page 50: Java Lab Programs

catch(collision e)

{

System.out.println(e);

t2=t1;

System.out.println("the collision has been avoided by redirection truck2");

}

catch(Exception e)

{

System.out.println(e); }

System.out.println("direction of truck1 :"+t1);

System.out.println("direction of truck2 :"+t2);

}

}

------------------------------------------------------------------

22. Write a program for generating 2 threads, one for printing even numbers and the other for printing odd numbers.

class even extends Thread

{

Thread t=null;

even()

{t=new Thread(this);

start();

}

public void run()

{try{for(int i=2;i<50;i+=2)

System.out.print(i+" ");

Thread.sleep(100);

}

Page 51: Java Lab Programs

catch(Exception e)

{System.out.println("thread interepted");}

}

}

class odd extends Thread

{

Thread t=null;

odd()

{

t=new Thread(this);

start();

}

public void run()

{try{for(int i=1;i<50;i+=2)

System.out.print(i+" ");

Thread.sleep(100);

}

catch(Exception e)

{System.out.println("thread interepted");}

}

}

class ThreadEvenOdd

{

public static void main(String arg[])

{

even e=new even();

odd o=new odd();

Page 52: Java Lab Programs

}

}

---------------------------------------------------------------------

23. Write a Java Applet program which reads your name and address in different text fields and when a button named find is pressed the sum of the length of characters in name and address is displayed in another text field.

import java.applet.*;

import java.awt.*;

import java.awt.event.*;/*<applet code="s09_01.class" width=400 height=400></applet>*/public class s09_01 extends Applet implements ActionListener {

public void init() {

label1 = new Label();

label2 = new Label();

label3 = new Label();

t1 = new TextField();

t2 = new TextField();

t3 = new TextField();

b1 = new Button();

setLayout(null);

setBackground(new Color(0, 153, 102));

label1.setAlignment(Label.RIGHT);

label1.setText("Name");

add(label1);

label1.setBounds(140, 60, 50, 20);

label2.setAlignment(Label.RIGHT);

label2.setText("Address");

add(label2);

label2.setBounds(140, 90, 50, 20);

Page 53: Java Lab Programs

label3.setAlignment(Label.RIGHT);

label3.setText("Total length");

add(label3);

label3.setBounds(130, 120, 60, 20);

add(t1);

t1.setBounds(200, 60, 100, 20);

add(t2);

t2.setBounds(200, 90, 100, 20);

add(t3);

t3.setBounds(200, 120, 100, 20);

b1.setBackground(new Color(255, 204, 153));

b1.setLabel("Total");

b1.addActionListener(this);

add(b1);

b1.setBounds(150, 180, 80, 24);

}

public void actionPerformed(ActionEvent ae)

{

int a=t1.getText().length();

a+=t2.getText().length();

t3.setText(Integer.toString(a));

}Label label1;

Label label2; Label label3; TextField t1; TextField t2; TextField t3; Button b1;

}

----------------------------------------------------------------------- THE END!!! ALL THE BEST EVERYONE -----------------------------------------------------------------------


Recommended