The document contains code for implementing various data structures and algorithms in Java, including a stack, queue, linked list, producer-consumer problem, scrolling text applet, and client-server file transfer program. The stack, queue, and linked list code demonstrates how to create the data structures and perform common operations like push, pop, insert, delete, and display. The producer-consumer code uses threads and synchronization to model the scenario. The scrolling text applet animates text moving across the screen. The client-server code allows a client to request a file from a server, which then sends the file contents to display on the client.
(1) c sharp introduction_basics_dot_netNico Ludwig
This presentation comes with many additional notes (pdf): http://de.slideshare.net/nicolayludwig/1-c-sharp-introductionbasicsdotnet-38638887
- History
- Bird's Eye View of Features
program list:
WAP program to show constructor overloading using static member.
WAP to implement multilevel inheritance and method overriding.
WAP to implement interface class and show use of package.
WAP to implement multilevel exception handling and create your own exception.
WAP to implement 3 threads such that 1st sleeps for 200ms, 2nd for 400ms and 3rd for 600ms.
WAP to create applet of moving banner.
WAP to make a simple calculator.
Build a client server chat application.
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfkostikjaylonshaewe47
Implement a queue using a linkedlist (java)
Solution
LinkedQueueImplement.java
import java.util.*;
class Node
{
protected int data;
protected Node link;
public Node()
{
link = null;
data = 0;
}
public Node(int d,Node n)
{
data = d;
link = n;
}
public void setLink(Node n)
{
link = n;
}
public void setData(int d)
{
data = d;
}
public Node getLink()
{
return link;
}
public int getData()
{
return data;
}
}
class linkedQueue
{
protected Node front, rear;
public int size;
public linkedQueue()
{
front = null;
rear = null;
size = 0;
}
public boolean isEmpty()
{
return front == null;
}
public int getSize()
{
return size;
}
/* Function to insert an element to the queue */
public void insert(int data)
{
Node nptr = new Node(data, null);
if (rear == null)
{
front = nptr;
rear = nptr;
}
else
{
rear.setLink(nptr);
rear = rear.getLink();
}
size++ ;
}
/* Function to remove front element from the queue */
public int remove()
{
if (isEmpty() )
throw new NoSuchElementException(\"Underflow Exception\");
Node ptr = front;
front = ptr.getLink();
if (front == null)
rear = null;
size-- ;
return ptr.getData();
}
/* Function to check the front element of the queue */
public int peek()
{
if (isEmpty() )
throw new NoSuchElementException(\"Underflow Exception\");
return front.getData();
}
/* Function to display the status of the queue */
public void display()
{
System.out.print(\"\ Queue = \");
if (size == 0)
{
System.out.print(\"Empty\ \");
return ;
}
Node ptr = front;
while (ptr != rear.getLink() )
{
System.out.print(ptr.getData()+\" \");
ptr = ptr.getLink();
}
System.out.println();
}
}
/* Class LinkedQueueImplement */
public class LinkedQueueImplement
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating object of class linkedQueue */
linkedQueue lq = new linkedQueue();
/* Perform Queue Operations */
System.out.println(\"Linked Queue Test\ \");
char ch;
do
{
System.out.println(\"\ Queue Operations\");
System.out.println(\"1. insert\");
System.out.println(\"2. remove\");
System.out.println(\"3. peek\");
System.out.println(\"4. check empty\");
System.out.println(\"5. size\");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println(\"Enter integer element to insert\");
lq.insert( scan.nextInt() );
break;
case 2 :
try
{
System.out.println(\"Removed Element = \"+ lq.remove());
}
catch (Exception e)
{
System.out.println(\"Error : \" + e.getMessage());
}
break;
case 3 :
try
{
System.out.println(\"Peek Element = \"+ lq.peek());
}
catch (Exception e)
{
System.out.println(\"Error : \" + e.getMessage());
}
break;
case 4 :
System.out.println(\"Empty status = \"+ lq.isEmpty());
break;
case 5 :
System.out.println(\"Size = \"+ lq.getSize());
break;
default :
System.out.println(\"Wrong Entry \ \");
break;
}
/* display queue */
lq.display();
System.out.println(\"\ Do you want to continue (Type y or n) \ \");
ch = scan.next().charAt(0);
} while (ch == \'Y\'|| ch == \'y\');
}
}
Output :
Linked Queue Test
Queue Operations
1. inse.
(1) c sharp introduction_basics_dot_netNico Ludwig
This presentation comes with many additional notes (pdf): http://de.slideshare.net/nicolayludwig/1-c-sharp-introductionbasicsdotnet-38638887
- History
- Bird's Eye View of Features
program list:
WAP program to show constructor overloading using static member.
WAP to implement multilevel inheritance and method overriding.
WAP to implement interface class and show use of package.
WAP to implement multilevel exception handling and create your own exception.
WAP to implement 3 threads such that 1st sleeps for 200ms, 2nd for 400ms and 3rd for 600ms.
WAP to create applet of moving banner.
WAP to make a simple calculator.
Build a client server chat application.
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfkostikjaylonshaewe47
Implement a queue using a linkedlist (java)
Solution
LinkedQueueImplement.java
import java.util.*;
class Node
{
protected int data;
protected Node link;
public Node()
{
link = null;
data = 0;
}
public Node(int d,Node n)
{
data = d;
link = n;
}
public void setLink(Node n)
{
link = n;
}
public void setData(int d)
{
data = d;
}
public Node getLink()
{
return link;
}
public int getData()
{
return data;
}
}
class linkedQueue
{
protected Node front, rear;
public int size;
public linkedQueue()
{
front = null;
rear = null;
size = 0;
}
public boolean isEmpty()
{
return front == null;
}
public int getSize()
{
return size;
}
/* Function to insert an element to the queue */
public void insert(int data)
{
Node nptr = new Node(data, null);
if (rear == null)
{
front = nptr;
rear = nptr;
}
else
{
rear.setLink(nptr);
rear = rear.getLink();
}
size++ ;
}
/* Function to remove front element from the queue */
public int remove()
{
if (isEmpty() )
throw new NoSuchElementException(\"Underflow Exception\");
Node ptr = front;
front = ptr.getLink();
if (front == null)
rear = null;
size-- ;
return ptr.getData();
}
/* Function to check the front element of the queue */
public int peek()
{
if (isEmpty() )
throw new NoSuchElementException(\"Underflow Exception\");
return front.getData();
}
/* Function to display the status of the queue */
public void display()
{
System.out.print(\"\ Queue = \");
if (size == 0)
{
System.out.print(\"Empty\ \");
return ;
}
Node ptr = front;
while (ptr != rear.getLink() )
{
System.out.print(ptr.getData()+\" \");
ptr = ptr.getLink();
}
System.out.println();
}
}
/* Class LinkedQueueImplement */
public class LinkedQueueImplement
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating object of class linkedQueue */
linkedQueue lq = new linkedQueue();
/* Perform Queue Operations */
System.out.println(\"Linked Queue Test\ \");
char ch;
do
{
System.out.println(\"\ Queue Operations\");
System.out.println(\"1. insert\");
System.out.println(\"2. remove\");
System.out.println(\"3. peek\");
System.out.println(\"4. check empty\");
System.out.println(\"5. size\");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println(\"Enter integer element to insert\");
lq.insert( scan.nextInt() );
break;
case 2 :
try
{
System.out.println(\"Removed Element = \"+ lq.remove());
}
catch (Exception e)
{
System.out.println(\"Error : \" + e.getMessage());
}
break;
case 3 :
try
{
System.out.println(\"Peek Element = \"+ lq.peek());
}
catch (Exception e)
{
System.out.println(\"Error : \" + e.getMessage());
}
break;
case 4 :
System.out.println(\"Empty status = \"+ lq.isEmpty());
break;
case 5 :
System.out.println(\"Size = \"+ lq.getSize());
break;
default :
System.out.println(\"Wrong Entry \ \");
break;
}
/* display queue */
lq.display();
System.out.println(\"\ Do you want to continue (Type y or n) \ \");
ch = scan.next().charAt(0);
} while (ch == \'Y\'|| ch == \'y\');
}
}
Output :
Linked Queue Test
Queue Operations
1. inse.
import java.util.;public class Program{public static void.pdfoptokunal1
import java.util.*;
public class Program
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x=\"X\";
int amount;
System.out.println(\"Enter amount\");
amount=input.nextInt();
System.out.println(\"Amount is: \"+amount);
for(int i=1; i<=amount; i++)
{
System.out.println(x);
for(int j=1; j<=i; j++)
{
System.out.print(x);
}
}
}
}
Why does It print out the last set of X\'s twice? I am doing basic Java so please try to explain
using the most basic codes.
import java.util.*;
public class Program
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x=\"X\";
int amount;
System.out.println(\"Enter amount\");
amount=input.nextInt();
System.out.println(\"Amount is: \"+amount);
for(int i=1; i<=amount; i++)
{
System.out.println(x);
for(int j=1; j<=i; j++)
{
System.out.print(x);
}
}
}
}
Why does It print out the last set of X\'s twice? I am doing basic Java so please try to explain
using the most basic codes.
import java.util.*;
public class Program
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x=\"X\";
int amount;
System.out.println(\"Enter amount\");
amount=input.nextInt();
System.out.println(\"Amount is: \"+amount);
for(int i=1; i<=amount; i++)
{
System.out.println(x);
for(int j=1; j<=i; j++)
{
System.out.print(x);
}
}
}
}
Why does It print out the last set of X\'s twice? I am doing basic Java so please try to explain
using the most basic codes.
Solution
Hi,
I have modified the code. it is working as expected now. Highlighted the code changes below.
Issue here is with you have written this statement twice System.out.println(x); which causes the
issue.
Program.java
import java.util.*;
public class Program
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String x=\"X\";
int amount;
System.out.println(\"Enter amount\");
amount=input.nextInt();
System.out.println(\"Amount is: \"+amount);
for(int i=1; i<=amount; i++)
{
System.out.println();
for(int j=1; j<=i; j++)
{
System.out.print(x);
}
}
}
}
Output:
Enter amount
10
Amount is: 10
X
XX
XXX
XXXX
XXXXX
XXXXXX
XXXXXXX
XXXXXXXX
XXXXXXXXX
XXXXXXXXXX.
Modify the Total program so that it writes the values in two columns.pdfsaxenaavnish1
Modify the Total program so that it writes the values in two columns, like this:
Previous answer Chegg provided displayed the correct output for in.txt but now, how do I make
the empty blank as shown?
Previous solution provided by Chegg:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Total {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.next();
String outputFileName = "out.txt";
File inputFile = new File(inputFileName);
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter(outputFileName);
double total = 0;
while (in.hasNext()) {
double value1 = in.hasNextDouble() ? in.nextDouble() : 0;
double value2 = in.hasNextDouble() ? in.nextDouble() : 0;
out.printf("%8.2f %7.2f%n", value1, value2);
total += (value1 + value2);
}
out.printf("Total: %10.2f%n", total);
in.close();
out.close();
}
} Your file content Your program produced no output Expected file content
1: Compare output Output differs. See highlights below. Special character legend 2: Compare
output A Input in2.txt.
public class TrequeT extends AbstractListT { .pdfinfo30292
/**
*/
public class Treque extends AbstractList {
/**
* You decide on the instance variables you need.
*/
public Treque(Class t) {
// Put your own code here
throw new UnsupportedOperationException(\"Constructor not yet implemented\");
}
public T get(int i) {
if (i < 0 || i > size() - 1) throw new IndexOutOfBoundsException();
// Put your own code here instead of throwing this exception
throw new UnsupportedOperationException(\"get(i) not yet implemented\");
}
public T set(int i, T x) {
if (i < 0 || i > size() - 1) throw new IndexOutOfBoundsException();
// Put your own code here instead of throwing this exception
throw new UnsupportedOperationException(\"set(i,x) not yet implemented\");
}
public void add(int i, T x) {
if (i < 0 || i > size()) throw new IndexOutOfBoundsException();
// Put your own code here
throw new UnsupportedOperationException(\"add(i,x) not yet implemented\");
}
public T remove(int i) {
if (i < 0 || i > size() - 1) throw new IndexOutOfBoundsException();
// Put your own code here
throw new UnsupportedOperationException(\"remove(i) not yet implemented\");
}
public int size() {
// Put your own code here
throw new UnsupportedOperationException(\"size() not yet implemented\");
}
public static void main(String[] args) {
//List tr = new ArrayDeque(Integer.class);
List tr = new Treque(Integer.class);
int K = 1000000;
Stopwatch s = new Stopwatch();
System.out.print(\"Appending \" + K + \" items...\");
System.out.flush();
s.start();
for (int i = 0; i < K; i++) {
tr.add(i);
}
s.stop();
System.out.println(\"done (\" + s.elapsedSeconds() + \"s)\");
System.out.print(\"Prepending \" + K + \" items...\");
System.out.flush();
for (int i = 0; i < K; i++) {
tr.add(0, i);
}
s.stop();
System.out.println(\"done (\" + s.elapsedSeconds() + \"s)\");
System.out.print(\"Midpending(?!) \" + K + \" items...\");
System.out.flush();
s.start();
for (int i = 0; i < K; i++) {
tr.add(tr.size()/2);
}
s.stop();
System.out.println(\"done (\" + s.elapsedSeconds() + \"s)\");
System.out.print(\"Removing \" + K + \" items from the back...\");
System.out.flush();
for (int i = 0; i < K; i++) {
tr.remove(tr.size()-1);
}
s.stop();
System.out.println(\"done (\" + s.elapsedSeconds() + \"s)\");
System.out.print(\"Removing \" + K + \" items from the front...\");
System.out.flush();
for (int i = 0; i < K; i++) {
tr.remove(0);
}
s.stop();
System.out.println(\"done (\" + s.elapsedSeconds() + \"s)\");
System.out.print(\"Removing \" + K + \" items from the middle...\");
System.out.flush();
for (int i = 0; i < K; i++) {
tr.remove(tr.size()/2);
}
s.stop();
System.out.println(\"done (\" + s.elapsedSeconds() + \"s)\");
}
}
-------------------------------------------------------------------
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
/**
* This class implements the List interface using a collection of arrays of
* sizes 1, 2, 3, 4, and so on. The main advantages of this over an
* implementation like ArrayList is that there is never more than O(sqr.
OrderTest.javapublic class OrderTest { Get an arra.pdfakkhan101
OrderTest.java
public class OrderTest {
/**
* Get an array of specified size and pass it to Order.order().
* Report the results.
*/
public static void main(String[] args) {
if (args.length != 1) {//1
System.out.println(\"Usage: java OrderTest sizeOfArray\ \"
+ \"\\tor\ \\tjava OrderTest arrayFile\");
System.exit(1);
}
// create or read the int[]
int size = 0;
int[] array = new int[0];//5
try {
size = Integer.parseInt(args[0]);
array = ArrayOfInts.randomizedArray(size);
} catch (NumberFormatException nfe) {//8
try {
array = ArrayOfInts.arrayFromFile(args[0]);
size = array.length;
} catch (Exception e) {
System.err.println(\"unable to read array from \" + args[0]);
System.exit(1);//14
}
}
System.out.println(\"before:\");//15
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? \" %d\" : \" %d\ \", array[i]);//1
}
int myNum = Order.order(array); //this is the call we want to measure
System.out.println(\"\ after:\");//18
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? \" %d\" : \" %d\ \", array[i]);
}
System.out.println(myNum);
}
}
ArrayOfInts.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ArrayOfInts {
/**
* Returns an array of consecutive ints from 1 to size.
*/
public static int[] orderedArray(int size) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = i+1;
}
return a;
}
/**
* Returns a randomized array containing ints from 1 to size.
*/
public static int[] randomizedArray(int size) {
ArrayList aL = new ArrayList();
for (int i = 0; i < size; i++) {
aL.add(i+1);
}
Collections.shuffle(aL);
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = aL.get(i);
}
return a;
}
/**
* Writes an int[] to a plain-text file with ints separated by spaces.
* Useful for creating input files for repeatable tests.
*/
public static void arrayToFile(int[] array, String outfile) {
try {
FileWriter fw = new FileWriter(outfile);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
for (int i : array) {
outFile.print(i + \" \");
}
outFile.close();
} catch (IOException e) {
System.err.println(\"Could not write to \" + outfile + \"\ \" + e);
}
}
/**
* Read ints from a file and return them in an int[]
*/
public static int[] arrayFromFile(String infile) throws FileNotFoundException,
InputMismatchException {
Scanner scan = new Scanner(new File(infile));
ArrayList aL = new ArrayList();
while (scan.hasNext()) {
aL.add(scan.nextInt());
}
scan.close();
int[] a = new int[aL.size()];
for (int i = 0; i < a.length; i++) {
a[i] = aL.get(i);
}
return a;
}
}
Order.java
public class Order {
/**
* Take an int[] and reorganize it so they are in ascending order.
*/
public static int order(int[] array) .
1. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
1. Program for implementing a stack & to perform Push & Pop
operations
import java.io.*;
class st
{
int top=0;
int max=0,i=0,n=0;
int stk[];
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
st()
{
try{
System.out.println("Enter the size of the stack");
max=Integer.parseInt(input.readLine());
}
catch(IOException e){}
stk=new int[max];
}
public void add()
{
try{
if(top<max)
{
System.out.println("Enter the element of the stack");
stk[top++]=Integer.parseInt(input.readLine());
}
else
System.out.println("Stack overflow");
}
catch(IOException e){}
}
public void delete()
{
if(top>0)
System.out.println("Deleted element is"+stk[--top]);
else
System.out.println("Stack underflow");
}
public void display()
{ if(top==0)
System.out.println("Stack is empty");
else
{
for(int i=0;i<top;i++)
System.out.println(" elements are"+stk[i]);
2. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
}
}
}
class Stack
{
public static void main(String args[])throws IOException
{
String data;
int ch=0;
st a=new st();
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
System.out.println("1:PUSH 2:POP 3:DISPLAY 4:EXIT");
System.out.println("Enter ur choice");
try{
ch=Integer.parseInt(input.readLine());
}
catch(IOException e){}
switch(ch)
{
case 1:a.add();
break;
case 2:a.delete();
break;
case 3:a.display();
break;
case 4:System.exit(0);
}
}
}
}
3. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
Output:
C:cd jdk1.3bin>javac Stack.java
C:JDK1.3BIN>java Stack
Enter the size of the stack
2
1:PUSH 2:POP 3:DISPLAY 4:EXIT
Enter ur choice
1
Enter the element of the stack
23
1:PUSH 2:POP 3:DISPLAY 4:EXIT
Enter ur choice
1
45
1:PUSH 2:POP 3:DISPLAY 4:EXIT
Enter ur choice
3
elements are 23
elements are 45
1:PUSH 2:POP 3:DISPLAY 4:EXIT
Enter ur choice
2
Deleted element is 45
1:PUSH 2:POP 3:DISPLAY 4:EXIT
Enter ur choice
4
C:JDK1.3BIN>
4. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
2. Program to implement the following operations on a Queue
Add an element
Delete an element
Display the elements
import java.io.*;
class Queue1
{
public static void main(String[] args)throws IOException
{
int a[]=new int [10];
int pos=0,n=0,j;
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
System.out.println("1.INSERTION");
System.out.println("2.DELETION");
System.out.println("3.DISPLAY");
System.out.println("4.EXIT");
System.out.println("enter your choice");
String choice = b.readLine();
if(choice.equals("1"))
{
System.out.println("enter the element");
String ma = b.readLine();
int d = Integer.parseInt(ma);
a[pos]=d;
pos++;
n++;
}
else
if(choice.equals("2"))
{
for(j=0;j<=pos-1;j++)
a[j]=a[j+1];
pos--;
n--;
}
else
if(choice.equals("3"))
{
if(n==0)
System.out.println("QUEUE EMPTY");
else
for(j=0;j<pos;j++)
System.out.println("Elements are:t" +a[j]);
6. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
Output:
C:JDK1.3BIN>java Queue1
1.INSERTION
2.DELETION
3.DISPLAY
4.EXIT
Enter your choice
1
Enter the element
2
1.INSERTION
2.DELETION
3.DISPLAY
4.EXIT
Enter your choice
1
Enter the element
5
1.INSERTION
2.DELETION
3.DISPLAY
4.EXIT
Enter your choice
3
Elements are: 2
Elements are:5
1.INSERTION
2.DELETION
3.DISPLAY
4.EXIT
Enter your choice
2
1.INSERTION
2.DELETION
3.DISPLAY
4.EXIT
Enter your choice
3
Elements are: 5
1.INSERTION
2.DELETION
3.DISPLAY
4.EXIT
Enter your choice
4
7. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
3. Program to implement the following operations on a singly linked list
Create a List
Add a Node to the Front of the List
Add a Node to the Back of the List
Delete a Specified Node
Display a List
import java.io.*;
import java.util.*;
class Link1
{
LinkedList l1=new LinkedList();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String input;
public void create(int size)throws IOException
{
for(int i=0;i<size;i++)
{
System.out.println("Enter the node item:");
input=br.readLine();
l1.add(input);
}
}
public void last()throws IOException
{
System.out.println("Enter the item to be inserted at the last:");
input=br.readLine();
l1.addLast(input);
}
public void begin()throws IOException
{
System.out.println("Enter the item to be inserted at the begining:");
input=br.readLine();
l1.addFirst(input);
}
public void delete()throws IOException
{
int pos;
System.out.println("Enter the position:");
input=br.readLine();
pos=Integer.parseInt(input);
8. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
l1.remove(pos);
}
public void display()
{
System.out.println("Elements in the list:");
System.out.println(l1);
}
}
class Link14
{
public static void main(String arg[])throws IOException
{
int choice;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Link1 l=new Link1();
while(true)
{
System.out.println("1.CREATE LINKED LIST");
System.out.println("2.ADD FIRST");
System.out.println("3.ADD LAST");
System.out.println("4.REMOVE");
System.out.println("5.DISPLAY");
System.out.println("6.EXIT");
System.out.println("Enter your choice:");
choice=Integer.parseInt(br.readLine());
switch(choice)
{
case 1:System.out.println("Enter the size:");
int s=Integer.parseInt(br.readLine());
l.create(s);
break;
case 2:l.begin();
break;
case 3:l.last();
break;
case 4:l.delete();
break;
case 5:l.display();
break;
case 6:System.exit(0);
default:System.out.println("Enter Proper Choice");
}
10. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
C:JDK1.3BIN>java Link14
1.CREATE LINKED LIST
2.ADD FIRST
3.ADD LAST
4.REMOVE
5.DISPLAY
6.EXIT
Enter your choice:
1
Enter the size:
2
Enter the node item:
4
Enter the node item:
-2
1.CREATE LINKED LIST
2.ADD FIRST
3.ADD LAST
4.REMOVE
5.DISPLAY
6.EXIT
Enter your choice:
2
Enter the item to be inserted at the beginning:
90
1.CREATE LINKED LIST
2.ADD FIRST
3.ADD LAST
4.REMOVE
5.DISPLAY
6.EXIT
Enter your choice:
5
Elements in the list:
[90, 4, -2]
1.CREATE LINKED LIST
2.ADD FIRST
3.ADD LAST
4.REMOVE
5.DISPLAY
6.EXIT
Enter your choice:
3
Enter the item to be inserted at the last:
10
11. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
1.CREATE LINKED LIST
2.ADD FIRST
3.ADD LAST
4.REMOVE
5.DISPLAY
6.EXIT
Enter your choice:
5
Elements in the list:
[90, 4, -2, 10]
1.CREATE LINKED LIST
2.ADD FIRST
3.ADD LAST
4.REMOVE
5.DISPLAY
6.EXIT
Enter your choice:
4
Enter the position:
2
1.CREATE LINKED LIST
2.ADD FIRST
3.ADD LAST
4.REMOVE
5.DISPLAY
6.EXIT
Enter your choice:
5
Elements in the list:
[90, 4, 10]
1.CREATE LINKED LIST
2.ADD FIRST
3 ADD LAST
4.REMOVE
5.DISPLAY
6.EXIT
Enter your choice:
6
C:JDK1.3BIN>
12. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
4. Program to implement a Producer and Consumer Problem using
Threads
import java.io.*;
class Q
{
int n;
boolean valueset=false;
synchronized int get()
{
if(!valueset)
try
{
wait();
}
catch (InterruptedException e1)
{
System.out.println("Thread Interrupted");
}
System.out.println("get" +n);
valueset=false;
notify();
return n;
}
synchronized void put(int n)
{
if(valueset)
try
{
wait();
}
catch (InterruptedException e2)
{
System.out.println("thread interrupted");
}
this.n=n;
valueset=true;
System.out.println("put " +n);
notify();
}
}
class Producer implements Runnable
{
Q q; Thread t;
Producer (Q q)
13. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
{
this.q=q;
t=new Thread(this, "Producer");
t.start();
}
public void run()
{
int i=0;
while (i<26)
{
q.put(i++);
}
}
}
class Consumer implements Runnable
{
Q q;Thread t;
Consumer (Q q)
{
this.q=q;
t=new Thread(this, "Consumer");
t.start();
}
public void run()
{
int i=0;
while(i < 26)
{
q.get();
}
}
}
class PC
{
public static void main(String args[])
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("press ctrl+c to exit");
}
}
14. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
Output:
C:JDK1.3BIN>javac PC.java
C:JDK1.3BIN>java PC
put 0
get0
put 1
get1
put 2
get2
put 3
get3
|
|
put 24
get24
put 25
get25
press ctrl+c to exit
C:JDK1.3BIN>
15. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
5. Program to create an applet to scroll a text message
import java.applet.*;
import java.awt.*;
public class AB extends Applet implements Runnable
{
String str;
int x,y;
public void init()
{
str="WELCOME TO RNSIT";
x=300;
y=100;
new Thread(this).start();
}
public void run()
{
try
{
while(true)
{
x=x-10;
if(x<0)
{
x=300;
}
repaint();
Thread.sleep(100);
}
} catch(InterruptedException e1){}
}
public void paint(Graphics g)
{
for(int i=0;i<10;i++)
g.drawString(str,x,y);
}
}
AB.html
<applet code=AB width=300 height=100>
</applet>
16. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
Output:
C:JDK1.3BIN>javac AB.java
C:JDK1.3BIN>appletviewer AB.html
Applet Viewer:AB
Applet
WELCOME TO RNSIT
Applet started.
17. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
6. Develop a Java program for a Client and Server Program to do the
following:
1.The client requests for a file.
2.The server sends the contents of the file requested.
3.The client receives the file and displays it.
// code for client program
import java.net.*;
import java.util.*;
import java.io.*;
public class Client
{
public static void main(String args[])
{
Socket client=null;
BufferedReader br=null;
try
{
System.out.println(args[0]+" "+ args[1]);
client=new Socket(args[0],Integer.parseInt(args[1]));
} catch(Exception e){}
BufferedReader input=null;
PrintStream output=null;
try
{
input=new BufferedReader(new InputStreamReader(client.getInputStream()));
output=new PrintStream(client.getOutputStream());
br=new BufferedReader(new InputStreamReader(System.in));
String str=input.readLine();//get the prompt from the server
System.out.println(str);//display the prompt on the client machine
String filename=br.readLine();
if(filename!=null)
output.println(filename);
String data;
while((data=input.readLine())!=null)
System.out.println(data);
client.close();
}
catch(Exception e)
{
System.out.println(e);
18. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
}
}
}
/* Code for Server program*/
import java.net.*;
import java.util.*;
import java.io.*;
public class Server
{
public static void main(String args[])
{
ServerSocket server=null;
try
{
server=new ServerSocket(Integer.parseInt(args[0]));
} catch(Exception e){}
while(true)
{
Socket client=null;
PrintStream output=null;
BufferedReader input=null;
try
{
client=server.accept();
} catch(Exception e){System.out.println(e);}
try
{
output=new PrintStream(client.getOutputStream());
input=new BufferedReader(new InputStreamReader(client.getInputStream())) ;
}catch(Exception e){System.out.println(e);}
//send the command Prompt to the client
output.println("ENTER THE FILE NAME>");
try
19. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
{
//get the file name from the client
String filename=input.readLine();
System.out.println("Client requested file:" + filename);
try
{
File f=new File(filename);
BufferedReader br=new BufferedReader(new FileReader(f));
String data;
while((data=br.readLine())!=null)
{
output.println(data);
}
}
catch(FileNotFoundException e)
{ output.println("FILE NOT FOUND");}
client.close();
}catch(Exception e){
System.out.println(e);
}
}
}
}
20. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
Output:
C:JDK1.3BIN>javac Client.java
C:JDK1.3BIN>javac Server.java
C:JDK1.3BIN>java Server 80
/* In a new prompt*/
C:JDK1.3BIN>java Client localhost 80
Local host 80
ENTER THE FILE NAME>
Server.java /*File Serever.java is displayed */
/*In the server prompt*/
Client requested file: Server.java
21. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
7. Program to implement the Simple Client/Server Application using
RM
/*Interface Program */
import java.rmi.*;
public interface TimeIntf extends Remote
{
public String getTime() throws RemoteException;
public void display() throws RemoteException;
}
/*Server Program */
import java.rmi.server.*;
import java.rmi.*;
import java.net.*;
import java.util.*;
import java.text.*;
public class TimeServer extends UnicastRemoteObject implements TimeIntf
{
TimeServer() throws Exception {}
public String getTime() throws RemoteException
{
Date dd=new Date();
SimpleDateFormat sdf;
sdf=new SimpleDateFormat("hh:mm:ss");
System.out.println("date&time"+sdf.format(dd));
String tt=sdf.format(dd);
return tt;
}
public void display() throws RemoteException
{
System.out.println("Hello This Is To Demonstrate RMI ");
}
public static void main (String args[] ) throws Exception
{
TimeServer tobj=new TimeServer();
Naming.rebind("Time",tobj);
}
}
22. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
/*Client Program */
import java.rmi.*;
public class TimeClient
{
public static void main(String args[]) throws Exception
{
TimeIntf t;
t=(TimeIntf)Naming.lookup("Time");
System.out.println(t.getTime());
t.display();
}
}
23. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
Output:
C:JDK1.3BIN>javac TimeIntf.java
C:JDK1.3BIN>javac TimeServer.java
C:JDK1.3BIN>javac TimeClient.java
C:JDK1.3BIN>rmic TimeServer
C:JDK1.3BIN>start rmiregistry
/*minimize the rmiregistry window & the prompt window*/
/*Open a new prompt window*/
C:JDK1.3BIN>java TimeClient
/*Using ALT+TAB switch to the other prompt window*/
C:JDK1.3BIN>java TimeServer
Java TimeSerever
date & time 02:19:09
Hello this is to demonstrate RMI
/*Open the client prompt using ALT+TAB */
date & time 02:19:12
24. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
8. Create a Java Servlet program to do the following:
1. To receive employee name & telephone number from the client
browser
2. To generate a response & send it to the client browser.
Create a HTML document to do the following:
1. To accept employee name & telephone number
2. To send them to Servlet
/* Servlet Program*/
import javax.servlet.*;
import java.io.*;
public class TestServlet extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response)
{
try{
PrintWriter out=response.getWriter();
String name=request.getParameter("name");
String phone=request.getParameter("phone");
out.println("<html>");
out.println("<body bgcolor=pink>");
out.println("Hello" +name);
out.println("<br><br>");
out.println("Your phone number is:" +phone);
out.println("</body></html>");
}
catch(Exception e){}
}
}
/*html Program*/
<html>
<body>
<form action="/examples/servlet/TestServlet" method="post">
Enter your name:<input type="text" name="name"><br><br>
Enter your Telphone no:<input type="text" name="phone"><br><br>
<input type="submit"value="submit">
<input type="reset" value="clear">
</form>
</body>
</html>
25. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
Output:
C:JDK1.3BIN>javac Test Servlet.java
/*Then a TestServlet.class file is created. Move this to the path below*/
C:Apache groupTomcat 4.1web appsWeb Inf classes TestServlet.class
/*similarly move the prg11.html file to the path below*/
C:Apache groupTomcat4.1 web apps root prg11.html
/* Now open the web browser*/
http://127.0.0.1:8080/prg11.html
Enter your name:
Enter your Telephone no:
submit clear
26. Downloaded from www.pencilji.com
Downloaded from www.pencilji.com
9. /*Create a HTML page to accept one of the three colors red,green, lue
& to send this o a Servlet. Write a Java program to create Servlet to
accept the color information sent by the client ‘s HTML page & to
generate a response.*/
/*Servlet Program*/
import java.io.*;
import javax.servlet.*;
public class pgm12 extends GenericServlet
{
public void service(ServletRequest request,ServletResponse response) throws
ServletException,IOException
{
PrintWriter out=response.getWriter();
String color=request.getParameter("r1");
out.println("<html>");
out.println("<body>");
out.println("<h1>The color you have choosen is :</h1> " +color);
out.println("</body></html>");
}
}
<!_HTML program_>
<html>
<body>
<form action="examples/servlet/pgm12" method="post">
<center>
<h3> Select any one color</h3>
<input type ="radio" name="r1" value="blue"> BLUE
<input type ="radio" name="r1" value="green"> Green
<input type ="radio" name="r1" value="red"> RED
<br><br>
<input type ="submit" value ="Submit">
</center>
</form>
</body>
</html>