Sunteți pe pagina 1din 42

Ex.

No: 1
Date :

IMPLEMENTATION OF RATIONAL NUMBERS

AIM
Develop Rational number class in Java. Use JavaDoc comment for
documentation. Your implementation should use efficient representation for a rational
number, i.e. (500 / 1000) should be represented as ().
ALGORITHM
Step 1:-

Declare a class called Rational and invoke a function called gcd(a,b).

Step 2:-

Find out the reminder when a is divided by b and pass it as a parameter to


the recursive function.

Step 3:-

Create an object for the class and declare the required string and integer
variables.

Step 4:-

Create an object of class DataInputStream .Read the numbers through the


readLine() method into the object.

Step 5:-

Convert the input accepted into Integers through the parseInt method and
store them in variables a and b.

Step 6:-

store the value returned by the function GCD in variable

l.
Step 7:-

Divide a by l and b by l and store them in variables x and y.

CODING:
import java.io.*; // import package io to perform I/O operation
class Rational1
{
public Rational1(){} // Default Constructor
public long gcd(long a,long b) // Recursive function to find the GCD
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
}
public class Rational
{
public static void main(String args[])throws IOException
{
Rational1 r=new Rational1();
long a,b,x,y;
String str;
DataInputStream in= new DataInputStream(System.in); // Create an IO stream
object to read the values
System.out.println("Enter the value for A");
str=in.readLine(); // Read a line of string
a=Integer.parseInt(str); // Converts from string to integer
System.out.println("Enter the value for B");
str=in.readLine();
b=Integer.parseInt(str);
long l=r.gcd(a,b); // call the gcd() method
System.out.println();
System.out.println("The GCD of the number is:"+l);

x=a/l;
y=b/l;
System.out.println();
System.out.println("The resultant value is: "+x+"/"+y); // Prints the ratio
}
}

RESULT
Thus the program Implementation of rational numbers has been successfully executed .

EX.NO:02
DATE:
IMPLEMENTATION OF DATE CLASS
AIM:
To develop Date class in Java similar to the one available in java.util package. Use JavaDoc
comments.
ALGORITHM:
Step 1:Declare a class called Dateexample and create an object called date.
Step 2:-Display the Date and Time through these objects with the Methods in Date
Class.
Step 3:-Declare two objects called starttime and endtime for this class .
Step 4:-Create another object called changed object and display the changed time
with the calculation 24L*60L*60L*1000L.
Step 5:-In the main function create object for the class Date and display the time and date
accordingly.

PROGRAM:
import java.io.*;
import java.util.Date;
public class Dateclass
{
public static void main(String args[])
{
Date d1=new Date();
try
{
Thread.sleep(10);
}
catch(Exception e)
{
}
Date d2=new Date();
System.out.println("First date:"+d1);
System.out.println("Second date:"+d2);
System.out.println("In second date after first:"+d2.after(d1));
int result=d1.compareTo(d2);
if(result>0)
System.out.println("First date is after second date");
else if(result<0)
System.out.println("First date is before second date");
else

System.out.println("Both are equal");


Date d=new Date(365L*24L*60L*60L*1000L);
System.out.println(d);
System.out.println("Milli Second since jan-1-1970 00:00:00:IST:"+d.getTime());
}
}

OUTPUT:
C:\ jdk1.6.0_17\bin>javac DateClass.java
C:\jdk1.6.0_17\bin>java DateClass
First date:Wed Sep 29 20:23:17 GMT+05:30 2010
Second date:Wed Sep 29 20:23:17 GMT+05:30 2010
In second date after first:true
First date is before second date
Fri Jan 01 05:30:00 GMT+05:30 1971
Milli Second since jan-1-1970 00:00:00:IST:31536000000

RESULT:

Thus the program Implementation of date class has been executed and verified
successfully.
EX.NO:03
DATE:
IMPLEMENTATION OF LISP-LIKE-LIST
AIM:
To implement Lisp-like list in Java. Write basic operations such as 'car', 'cdr', and
'cons'. If L is a list [3, 0, 2, 5], L.car() returns 3, while L.cdr() returns [0,2,5].
ALGORITHM:
STEP 1: Create a node of a list having data part and link part.
STEP 2: Create a menu having the following choices : insert, car, cdr, adjoin and
display.
STEP 3: Read the choice from the user and call the respective m ethods.
STEP 4: Create another class which implements the same interface to implement the
concept of stack through linked list.
INSERT
STEP 1: Create an object of node and append to the list.
CAR
STEP 1: Return the first node data.
CDR
STEP 1: Return all the node (data part) in the list except the first node.
ADJOIN
STEP 1: Check if the node to be inserted is already present in the list, if not present
append to the list.
PROGRAM:
import java.util.*;
class Lisp
{
public int car(List l)
{
Object ob=l.get(0);
String st=ob.toString();

return Integer.parseInt(st);
}
public List cdr(List l)
{
Object ob=l.remove(0);
Object obj[]=l.toArray();
List list=Arrays.asList(obj);
return list;
}
public static void main(String[] args)
{
List <Integer>l=new ArrayList<Integer>();
l.add(3);
l.add(0);
l.add(2);
l.add(5);
Lisp L=new Lisp();
int val=L.car(l);
System.out.println(val);
List list=L.cdr(l);
System.out.println(list);
}
}

OUTPUT:
C:\jdk1.6.0_17\bin>javac Lisp.java
C:\jdk1.6.0_17\bin>java Lisp
3
[0, 2, 5]
C:\jdk1.6.0_17\bin>

RESULT:

Thus the program Implementation of lisp-like-list has been successfully executed.


EX.NO:04
DATE:
IMPLEMENTATION OF STACK ADT USING INTERFACE
AIM

EX.NO:05
DATE:
IMPLEMENTATION OF POLYMORPHISM
AIM:
To design a Vehicle class hierarchy in Java. Write a test program to demonstrate
Polymorphism.
ALGORITHM

CODING
import java.io.*;
public class VehicleTest
{
public static void main(String[] args)
{
Vehicle ce=new Corvette("Corvette","red",545000);
Vehicle be=new Bettle("Bettle","blue",445000);
Vehicle pe=new Porsche("Porsche","black",625000);
Vehicle vehicle=new Vehicle();

System.out.println("Name="+ce.getName()+"\nColor="+ce.getColor()+"\nPrice="+ce.getPrice()
+"\n\n");
System.out.println("Name="+be.getName()+"\nColor="+be.getColor()+"\nPrice="+be.getPrice()
+"\n\n");
System.out.println("Name="+pe.getName()+"\nColor="+pe.getColor()+"\nPrice="+pe.getPrice()
+"\n\n");
}
}
class Vehicle
{
String name;
String color;
double price;
public Vehicle()
{
name="";
color=" ";
price=0;
}
public Vehicle(String name,String color,double price)
{
this.name=name;
this.color=color;
this.price=price;
}
public String getName()
{
return name;
}
public String getColor()
{
return color;
}
public double getPrice()
{
return price;
}
}
class Bettle extends Vehicle
{
public Bettle(String name,String color,double price)
{
super(name,color,price);
}
}
class Corvette extends Vehicle

{
public Corvette(String name,String color,double price)
{
super(name,color,price);
}
}
class Porsche extends Vehicle
{
public Porsche(String name,String color,double price)
{
super(name,color,price);
}
}

OUTPUT:
C:\jdk1.6.0_17\bin>javac VehicleTest.java
C:\jdk1.6.0_17\bin>java VehicleTest
Name=Corvette
Color=red
Price=545000.0
Name=Bettle
Color=blue
Price=445000.0
Name=Porsche
Color=black
Price=625000.0
C:\jdk1.6.0_17\bin>

RESULT:
Thus the program Implementation of polymorphism has been successfully executed.

Ex No:-6

Object Serialization

Aim:-To write a Java Program to randomly generate objects and write them
into a file
using concept of Object Serialization.
Algorithm:Step 1:Declare a class called Currency .Open a file in output mode with a
name.
Step 2:-Write new data into the object using writeobject() method.
Step 3:-Similarly create an input stream object .Read it both in terms of
Dollars and
Rupees.close the output object.
Step 4:-derive a class called Dollar which implements serializable
interface.Invoke a
constructor and function to display the data.
Step 5:Similarly declare a class called Rupee with private variables and use
print function to display the variables.
Step 6:terminate the execution.The output is displayed as dollar to rupee
conversion and vice versa.
CODING
// Currency conversion
import java.io.*;
public class Currency
{
public static void main(String args[])
{
Dollar dr=new Dollar('$',40);
dr.printDollar();
Rupee re=new Rupee("Rs.",50);
re.printRupee();
try
{
File f=new File("rd.txt");
FileOutputStream fos=new FileOutputStream(f);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(dr);
oos.writeObject(re);
oos.flush();

oos.close();
ObjectInputStream ois=new ObjectInputStream(new
FileInputStream("rd.txt"));
Dollar d1;
d1=(Dollar)ois.readObject();
d1.printDollar();
Rupee r1;
r1=(Rupee)ois.readObject();
r1.printRupee();
ois.close();
}
catch(Exception e)
{
}
}
} class Dollar implements Serializable
{
private float dol;
private char sym;
public Dollar(char sm,float doll)
{
sym=sm;
dol=doll;
}
void printDollar()
{
System.out.print(sym);
System.out.println(dol);
}
} class Rupee implements Serializable
{
private String sym;
private float rs;
public Rupee(String sm,float rup)
{
sym=sm;
rs=rup;
}
void printRupee()
{
System.out.print(sym);
System.out.println(rs);
}
}

Output:E:\java>java Currency
$40.0
Rs.50.0
$40.0
Rs.50.0

RESULT
Thus the Java Program to randomly generate objects and write them
into a file
using concept of Object Serialization
EX.NO:07
DATE:
IMPLEMENTATION OF SCENTIFIC CALCULATOR USING
EVENT DRIVEN PROGRAMMING
AIM:
To develop a scientific calculator using even-driven programming paradigm of Java.
ALGORITHM:
STEP 1: Create a panel consisting of Buttons for various scientific operations.
STEP 2: Create Button actions.
STEP 3: Place the panel onto a frame.
STEP 4: Associate each Button click with the corresponding actionlistener.
PROGRAM:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
public class Calculator
{
public static void main(String[] args)
{
CalculatorFrame frame = new CalculatorFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class CalculatorFrame extends JFrame
{
public CalculatorFrame()

{
setTitle("Calculator");
CalculatorPanel panel = new CalculatorPanel();
add(panel);
pack();
}
}
class CalculatorPanel extends JPanel
{
public CalculatorPanel()
{
setLayout(new BorderLayout());
result = 0;
lastCommand = "=";
start = true;
display = new JButton("0");
display.setEnabled(false);
add(display, BorderLayout.NORTH);
ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();
panel = new JPanel();
panel.setLayout(new GridLayout(6,5));
addButton("7", insert);
addButton("8", insert);
addButton("9", insert);
addButton("/", command);
addButton("CE", command);
addButton("4", insert);
addButton("5", insert);
addButton("6", insert);
addButton("*", command);
addButton("m+", command);
addButton("1", insert);
addButton("2", insert);
addButton("3", insert);
addButton("-", command);
addButton("m-", command);
addButton("0", insert);
addButton(".", insert);
addButton("+/-", command);
addButton("+", command);
addButton("n!", command);

addButton("pow", command);
addButton("1/x", insert);
addButton("SQRT", insert);
addButton("log", insert);
addButton("%", command);
addButton("sin", insert);
addButton("cos", insert);
addButton("tan", insert);
addButton("x2", insert);
addButton("=", command);
add(panel, BorderLayout.CENTER);
}
private void addButton(String label, ActionListener listener)
{
JButton button = new JButton(label);
button.addActionListener(listener);
panel.add(button);
}
private class InsertAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String input = event.getActionCommand();
if (start==true)
{
display.setText("");
start = false;
}
if(input.equals("1/x"))
display.setText(""+1/Double.parseDouble(display.getText()));
else
if(input.equals("SQRT"))
display.setText(""+Math.sqrt(Double.parseDouble(display.getText())));
else
if(input.equals("log"))
display.setText(""+Math.log(Double.parseDouble(display.getText())));
else
if(input.equals("x2"))
display.setText(""+Double.parseDouble(display.getText())*
Double.parseDouble(display.getText()));

else
if(input.equals("sin"))
{
Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0;
display.setText(""+Math.sin(angle));
}
else if(input.equals("cos"))
{
Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0;
display.setText(""+Math.cos(angle));
}
else
if(input.equals("tan"))
{
Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0;
display.setText(""+Math.tan(angle));
}
else
display.setText(display.getText() + input);
}
}
private class CommandAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if (start==true)
{
if (command.equals("-"))
{
display.setText(command);
start = false;
}
else
lastCommand = command;
}
else
{
calculate(Double.parseDouble(display.getText()));
lastCommand = command;
start = true;
}
}
}
public void calculate(double x)

{
if (lastCommand.equals("+")) result += x;
else if (lastCommand.equals("-")) result -= x;
else if (lastCommand.equals("*")) result *= x;
else if (lastCommand.equals("/")) result /= x;
else if (lastCommand.equals("=")) result = x;
else if (lastCommand.equals("CE")) result = 0.0;
else if (lastCommand.equals("m+")) result = result;
else if (lastCommand.equals("m-")) result = 0.0;
else if (lastCommand.equals("pow"))
{
double powval=1.0;
for(double i=0.0;i<x;i++)
powval*=result;
result=powval;
}
display.setText(""+ result);
}
private JButton display;
private JPanel panel;
private double result;
private String lastCommand;
private boolean start;
}

OUTPUT:
C:\jdk1.6.0_17\bin>javac Calculator.java
C:\jdk1.6.0_17\bin>java Calculator
C:\jdk1.6.0_17\bin>

RESULT:
Thus the program Implementation of scientific calculator using event driven programming has
been successfully executed .
EX.NO:08
DATE:
IMPLEMENTATION OF MULTI THREADED PROGRAM
AIM:
To write a multi-threaded Java program to print all numbers below 100,000 that are
both prime and fibonacci number (some examples are 2, 3, 5, 13, etc.). Design a
thread that generates prime numbers below 100,000 and writes them into a pipe.
Design another thread that generates fibonacci numbers and writes them to another
pipe. The main thread should read both the pipes to identify numbers common to
both.
ALGORITHM:
STEP 1: CreateThread1 which generates prime numbers below 100,000 and store in
pipe1.
STEP 2: Create Thread2 which generates Fibonacci numbers below 100,000 and store in
pipe 2.
STEP 3: Write a main program which does the following:
(i)
Call the two threads created in step1 and step2.
(ii)
Read the data from pipe1 and pipe 2 and print the numbers common to both.

PROGRAM:
import java.util.*;
import java.io.*;
class Fibonacci extends Thread
{
private PipedWriter out=new PipedWriter();
public PipedWriter getPipedWriter()
{
return out;
}
public void run()
{
Thread t=Thread.currentThread();
t.setName("Fibonacci:");
System.out.println(t.getName()+"Thread stored......");
int fibo1=0,fibo2=1,fibo=0;
while(true)
{
try
{
fibo=fibo1+fibo2;
if(fibo>100000)
{
out.close();
break;
}
out.write(fibo);
sleep(1000);
}
catch(Exception e)
{
System.out.println("Fibonacci:"+e);
}
fibo1=fibo2;
fibo2=fibo;
}
System.out.println(t.getName()+"Thread exiting.");
}
}
class Prime extends Thread
{
private PipedWriter out1=new PipedWriter();
public PipedWriter getPipedWriter()

{
return out1;
}
public void run()
{
Thread t=Thread.currentThread();
t.setName("Prime:");
System.out.println(t.getName()+"Thread stored.......");
int prime=1;
while(true)
{
try
{
if(prime>100000)
{
out1.close();
break;
}
if(isPrime(prime))
out1.write(prime);
prime++;
sleep(0);
}
catch(Exception e)
{
System.out.println(t.getName()+"Thread exiting.");
System.exit(0);
}
} }
public boolean isPrime(int n)
{
int m=(int)Math.round(Math.sqrt(n));
if(n==1||n==2)
return true;
for(int i=2;i<=m;i++)
if(n%i==0)
return false;
return true;
}
}
public class PipedIo
{
public static void main(String[] args)throws Exception
{
Thread t=Thread.currentThread();
t.setName("Main:");

System.out.println(t.getName()+"Thread sorted......");
Fibonacci fibonacci=new Fibonacci();
Prime prime=new Prime();
PipedReader fpr=new PipedReader(fibonacci.getPipedWriter());
PipedReader ppr=new PipedReader(prime.getPipedWriter());
fibonacci.start();
prime.start();
int fib=fpr.read(),prm=ppr.read();
System.out.println("The Numbers Common To PRIME and FIBONACCI:");
while ((fib!=-1)&&(prm!=-1))
{
while(prm<=fib)
{
if(fib==prm)
System.out.println(prm);
prm=ppr.read();
}
fib=fpr.read();
}
System.out.println(t.getName()+"Thread exiting.");
} }
OUTPUT:
C:\jdk1.6.0_17\bin>javac PipedIo.java
C:\jdk1.6.0_17\bin>java PipedIo
Main:Thread sorted......
Fibonacci:Thread stored......
Prime:Thread stored.......
The Numbers Common To PRIME and FIBONACCI:
1
2
3
5
13
89
233
1597
28657
Fibonacci:Thread exiting.
Main:Thread exiting.
Prime:Thread exiting.
C:\jdk1.6.0_17\bin>

RESULT:
Thus the program Implementation of multi threaded program to find Fibonacci series has been
Successfully executed .

EXP: NO. 9

Simple OPAC system for library

DATE:
AIM:
To develop a simple OPAC system for library using event-driven and concurrent
programming paradigms of Java. JDBC is used to connect to a back-end database.
ALGORITHM:
Step 1: Start the program.
Step 2: Design the front end for the library system.
Step 3: Connect the front end with the database at the backend using JDBC.
Step 4: Design the front end such that it accepts the inputs from the user and inserts the records
into the database.
Step 5: Display the contents of the database at the front end.
Step 6: Suspend the established connections.
Step 7: Stop the program.

PROGRAM:
Datas.java
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Datas extends JFrame implements ActionListener
{
JTextField id;
JTextField name;
JButton next;
JButton addnew;
JPanel p;
static ResultSet res;
static Connection conn;
static Statement stat;
public Datas()
{
super("Our Application");
Container c = getContentPane();
c.setLayout(new GridLayout(5,1));
id = new JTextField(20);
name = new JTextField(20);
next = new JButton("Next BOOK");
p = new JPanel();
c.add(new JLabel("ISBN",JLabel.CENTER));
c.add(id);
c.add(new JLabel("Book Name",JLabel.CENTER));
c.add(name);
c.add(p);
p.add(next);
next.addActionListener(this);
pack();
setVisible(true);
addWindowListener(new WIN());
}
public static void main(String args[])
{
Datas d = new Datas();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:custo");
stat = conn.createStatement();

res = stat.executeQuery("Select * from stu");


res.next();
}
catch(Exception e)
{
System.out.println("Error" +e);
}
d.showRecord(res);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == next)
{
try
{
res.next();
}
catch(Exception ee)
{
}
showRecord(res);
}
}
public void showRecord(ResultSet res)
{
try
{
id.setText(res.getString(2));
name.setText(res.getString(3));
}
catch(Exception e)
{
}
}
class WIN extends WindowAdapter
{
public void windowClosing(WindowEvent w)
{
JOptionPane jop = new JOptionPane();
jop.showMessageDialog(null,"Database","Thanks",JOptionPane.QUESTION_MESSAGE);
}
}
}

Prog1.java
import java.sql.*;
import java.sql.DriverManager.*;
class Ja
{
String bookid,bookname;
int booksno;
Connection con;
Statement stmt;
ResultSet rs;
Ja()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:co");
}
catch(Exception e)
{
System.out.println("connection error");
}
}
void myput()
{
try
{
stmt=con.createStatement();
rs=stmt.executeQuery("SELECT * FROM opac");
while(rs.next())
{
booksno=rs.getInt(1);
bookid=rs.getString(2);
bookname=rs.getString(3);
System.out.println("\n"+ booksno+"\t"+bookid+"\t"+bookname);
}
rs.close();
stmt.close();
con.close();
}
catch(SQLException e)
{
System.out.println("sql error");
}
}
}

class prog1
{
public static void main(String arg[])
{
Ja j=new Ja();
j.myput();
}
}
OUTPUT:

RESULT:
Thus the program to design a simple OPAC system for library was executed and the
output was verified successfully.

Ex:10.Multi-threaded Echo Server and Client in Java.


Aim:-To develop a Java Program that supports multithreaded echo
server and a GUI client.
Algorithm:Step 1:-Import the net package which supports networking features
in Java.
Step 2:-Write the input data into an object from the keyboard
through BufferedStream class.
Step 3:-Create a new object for Socket s and Write the input data
into another object called dos using writeBytes() method.
Step 4:-Read the copied string into br using readLine() method
and close the file.
Step 5:-On executing the program,the server sends a message to
the client.
Step 6:-For the server side program, create an object for
ServerSocket class and write input data into it.
Step 7:-Write the data into the dataoutputstream object dos.
Step 8:-close the object and socket.

// Client Program:import java.net.*;


import java.io.*;
class Client
{
public static void main(String args[])throws IOException
{
Socket soc=null;
String str=null;
BufferedReader br=null;
DataOutputStream dos=null;
BufferedReader kyrd=new BufferedReader(new
InputStreamReader(System.in));
try
{
soc=new Socket(InetAddress.getLocalHost(),95);
br=new BufferedReader(new InputStreamReader(soc.getInputStream()));
dos=new DataOutputStream(soc.getOutputStream());
}
catch(UnknownHostException uhe)
{
System.out.println("Unknown Host");
System.exit(0);
}
System.out.println("To start the dialog type the message in this client
window \n
Type exit to end");
boolean more=true;
while(more)

{
str=kyrd.readLine();
dos.writeBytes(str);
dos.write(13);
dos.write(10);
dos.flush();
String s,s1;
s=br.readLine();
System.out.println("From server :"+s);
if(s.equals("exit"))
break;
}
br.close();
dos.close();
soc.close();
}
}
// Server Program
import java.net.*;
import java.io.*;
class Server
{
public static void main(String args[])throws IOException
{
ServerSocket ss=null;
try
{
ss=new ServerSocket(95);
}
catch(IOException ioe)
{
System.out.println("Error finding port");
System.exit(1);
}
Socket soc=null;
try
{
soc=ss.accept();
System.out.println("Connection accepted at :"+soc);
}
catch(IOException ioe)
{
System.out.println("Server failed to accept");
System.exit(1);
}

DataOutputStream dos=new DataOutputStream(soc.getOutputStream());


BufferedReader br=new BufferedReader(new
InputStreamReader(soc.getInputStream()));
String s;
System.out.println("Server waiting for message from tthe client");
boolean quit=false;
do
{
String msg="";
s=br.readLine();
int len=s.length();
if(s.equals("exit"))
quit=true;
for(int i=0;i<len;i++)
{
msg=msg+s.charAt(i);
dos.write((byte)s.charAt(i));
}
System.out.println("From client :"+msg);
dos.write(13);
dos.write(10);
dos.flush();
}while(!quit);
dos.close();
soc.close();
}
}
Output:E:\java>java Client
To start the dialog type the message in this client window
Type exit to end
hello
From server :hello
how are you
From server :how are you
how are you
From server :how are you
exit
From server :exit
E:\java>java Server
Connection accepted at :Socket[addr=/127.0.0.1,port=49442,localport=95]
Server waiting for message from tthe client
From client :hello

From client :how are you


From client :how are you
From client :exit

MiniProject
Aim:
To Develop a programmer's editor in Java that supports syntax highlighting, compilation
support, debugging support, etc
Program:
/*********************** PROGAMMERS EDITOR IN JAVA************************/ /*
Client Frame Design with width=600 & height=500*/
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.text.Element;
import java.util.StringTokenizer;
public class Client implements ActionListener,MouseListener,MouseMotionListener
{
/************ Components *****************/
JFrame frame;
JTextArea jta1;
public JTextArea jta2;
JTextArea jta3;
JButton jb1;
JButton jb2;
JButton jb3;
JButton jb4;
JLabel jl1;
JLabel jl2;
JLabel jl3;
JScrollPane jsp1;
JScrollPane jsp2;
JScrollPane jsp3;
JTabbedPane jtp1;

JTabbedPane jtp2;
JTabbedPane jtp3;
JMenuBar jm;
JMenu open;
JMenu exit;
JMenu file;
JMenu help;
JMenu compile;
JMenu run;
JMenu opt;
/************ Variables *****************/
String line;
String option;
String className;
String pureFile;
File f2;
File f3;
public Client()
{
frame=new JFrame("XDoS Compiler");
frame.setLayout(null);
frame.setBounds(300,10,200,200);
frame.setSize(900,650);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jta1=new JTextArea(300,400);
jsp1=new JScrollPane(jta1);
jsp1.setBounds(10, 10, 670, 200);
jsp1.setEnabled(false);
Border etchedBdr1 = BorderFactory.createEtchedBorder();
jta1.setBorder(etchedBdr1); //frame.add(jsp1);
jta2=new JTextArea(300,400);
jsp2=new JScrollPane(jta2);
jsp2.setBounds(10, 280, 670, 150);
Border etchedBdr2 = BorderFactory.createEtchedBorder();
jta2.setBorder(etchedBdr2);
jta2.setEditable(false);
//frame.add(jsp2);
jta3=new JTextArea(300,400);
jsp3=new JScrollPane(jta3);
jsp3.setBounds(10, 450, 670, 150);
Border etchedBdr3 = BorderFactory.createEtchedBorder();
jta3.setBorder(etchedBdr3);
//frame.add(jsp3);
jl1=new JLabel();
jl1.setBounds(500, 380, 670, 150);
frame.add(jl1);
jl2=new JLabel();

jl2.setBounds(550, 380, 670, 150);


frame.add(jl2);
jl3=new JLabel();
jl3.setBounds(600, 380, 670, 150);
frame.add(jl3);
jb1=new JButton("Browse");
jb1.setBounds(50, 235, 100, 20);
jb1.addActionListener(this);
//frame.add(jb1);
jb2=new JButton("compile");
jb2.setBounds(200, 235, 100, 20);
jb2.addActionListener(this);
//frame.add(jb2); jb3=new JButton("Send");
jb3.setBounds(550, 235, 100, 20);
jb3.addActionListener(this);
//frame.add(jb3);
jb4=new JButton("Run");
jb4.setBounds(400, 235, 100, 20);
jb4.addActionListener(this);
//frame.add(jb4);
jtp1=new JTabbedPane();
jtp1.addTab( "untitled.java", jsp1 );
jtp1.setBounds(10, 40, 670, 400);
UIManager.put("TabbedPane.selected", Color.green);
jtp1.set ForegroundAt(0,Color.BLUE);
jtp1.setBackgroundAt(0,Color.BLUE);
frame.add(jtp1); jtp2=new JTabbedPane();
jtp2.addTab( "Result", jsp2 );
jtp2.setBounds(10, 450, 670, 150);
frame.add(jtp2); jtp3=new JTabbedPane();
jtp3.addTab( "Reply", jsp3 );
jtp3.setBounds(700, 40, 180, 560);
frame.add(jtp3); jm=new JMenuBar();
file=new JMenu("File");
file.setMnemonic('F');
opt=new JMenu("Option");
opt.setMnemonic('O');
opt.setEnabled(false);
jm.add(file);
jm.add(opt);
compile=new JMenu("Compile");
compile.setMnemonic('C');
Action action3 = new AbstractAction("Compile")
{
public void actionPerformed(ActionEvent e)
{
compile();
}

};
JMenuItem item3 = file.add(action3);
opt.add(item3);
run=new JMenu("Run");
run.setMnemonic('R');
Action action4 = new AbstractAction("Run")
{
public void actionPerformed(ActionEvent e)
{
run();
}
};
JMenuItem item4 = file.add(action4);
opt.add(item4); help=new JMenu("Help");
jm.add(help); open=new JMenu("open");
Action action1 = new AbstractAction("Open")
{
public void actionPerformed(ActionEvent e)
{ open(); } };
JMenuItem item1 = file.add(action1);
file.add(item1); exit=new JMenu("Exit");
Action action2 = new AbstractAction("Exit")
{
public void actionPerformed(ActionEvent e)
{
System.exit(0); } };
JMenuItem item2 = file.add(action2);
file.add(item2);
jm.setBounds(5, 0, 880, 30);
frame.add(jm);
frame.setResizable(false);
frame.setVisible(true);
jta1.addMouseListener(this);
jta1.addMouseMotionListener(this);
jtp1.addMouseListener(this); jtp2.addMouseListener(this);
}
public void mouseClicked(MouseEvent ew)
{
if(ew.getSource()==jta1)
{
jl3.setText("Line-No: "+Integer.toString(getCurrentLineNumber()));
}
else if(ew.getSource()==jtp2)
{
if(jtp1.isShowing())
{
frame.remove(jtp1);
jtp2.setBounds(10, 40, 670, 560);

jl1.setBounds(500, 535, 670, 150);


jl2.setBounds(550, 535, 670, 150);
jl3.setBounds(600, 535, 670, 150);
jta2.addMouseMotionListener(this);
jl3.setText("Line-No: "+Integer.toString(getCurrentLineNumber()));
}
else { frame.add(jtp1);
jtp2.setBounds(10, 450, 670, 150);
jl1.setBounds(500, 380, 670, 150);
jl2.setBounds(550, 380, 670, 150);
jl3.setBounds(600, 380, 670, 150);
jta2.removeMouseMotionListener(this);
}}
else if(ew.getSource()==jtp1)
{
if(jtp2.isShowing())
{ frame.remove(jtp2);
frame.remove(jtp3); jtp1.setBounds(10, 40, 870, 560);
jl1.setBounds(500, 535, 670, 150);
jl2.setBounds(550, 535, 670, 150);
jl3.setBounds(600, 535, 670, 150);
}
else { frame.add(jtp2); frame.add(jtp3);
jtp1.setBounds(10, 40, 670, 400);
jl1.setBounds(500, 380, 670, 150);
jl2.setBounds(550, 380, 670, 150);
jl3.setBounds(600, 380, 670, 150); } } }
public void mouseEntered(MouseEvent ew)
{} public void mouseExited(MouseEvent ew) {}
public void mousePressed(MouseEvent ew) {}
public void mouseReleased(MouseEvent ew) {}
public void mouseMoved(MouseEvent e)
{ jl1.setText("X-: "+Integer.toString(e.getX()));
jl2.setText("Y-: "+Integer.toString(e.getY())); }
public void mouseDragged(MouseEvent e) {}
public void actionPerformed(ActionEvent ae) {}
public void open()
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.addChoosableFileFilter(new MyFilter());
int select=fileChooser.showOpenDialog(frame);
if(select==JFileChooser.APPROVE_OPTION) {
File file=fileChooser.getSelectedFile();
String filename=fileChooser.getSelectedFile().getName();
try { FileInputStream fis=new FileInputStream(file);
int n=fis.available(); byte dat[]=new byte[n];
fis.read(dat); String data=new String(dat);
jtp1.setTitleAt(0, filename);

jta1.setText(data); opt.setEnabled(true); }
catch(Exception e)
{ e.printStackTrace(); } }
}
public int getCurrentLineNumber()
{
int line;
int caretPosition = jta1.getCaretPosition();
Element root = jta1.getDocument().getDefaultRootElement();
line = root.getElementIndex(caretPosition) + 1; return line;
}
public void compile() { try { jtp2.setTitleAt(0,"Compile");
String ta1=jta1.getText().trim();
StringBuffer sb=new StringBuffer(ta1);
int id1=ta1.indexOf("public class");
int id2=ta1.indexOf(" ",id1+13);
String name=ta1.substring(id1, id2).trim();
StringTokenizer st3=new StringTokenizer(name,"\n");
System.out.println(st3.countTokens());
String word=st3.nextToken().toString().trim(); System.out.println(word+"*");
StringTokenizer st4=new StringTokenizer(word," "); System.out.println(st4.countTokens());
st4.nextToken(); st4.nextToken();
pureFile=st4.nextToken().toString().trim();
className=pureFile+".java"; //System.out.println(st4.nextElement().toString().trim()+"*");
FileOutputStream f=new FileOutputStream(className);
f.write(ta1.getBytes());
f.close();
f2=new File(className); f3=new File(pureFile+".class");
System.out.println(f2.getAbsolutePath());
String path=f2.getAbsolutePath(); int a1=path.indexOf("\\");
int a2=path.lastIndexOf("\\");
System.out.println(a1+" "+a2);
String colan=path.substring(0, a1).trim();
String location=path.substring(0, a2+1).trim();
System.out.println(colan);
System.out.println(location);
compiler(className); }
catch (Exception err)
{ err.printStackTrace();
} //option=JOptionPane.showInputDialog(null,"Enter Destination System
Name","Destination",1).toString(); //System.out.println(option); // jta2.setText(line); }
public void run() { jtp2.setTitleAt(0,"Run");
runer(pureFile); }
public static void main(String args[])
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");

}
catch (Exception e) { } new Client(); }
public void compiler(String name)
{ try { jta2.setText("");
jta2.append("Compilation Started.....\n");
jta2.append("Proceed.....\n");
jta2.setForeground(Color.blue);
String callAndArgs= "cmd /c compile.bat "+name; Process p
=Runtime.getRuntime().exec(callAndArgs);
BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
String str=br.readLine();
while(str!=null)
{
System.out.println(str);
str=br.readLine(); }
File f1 = new File("error.txt");
FileReader fr = new FileReader(f1);
BufferedReader br1 = new BufferedReader(fr);
StringBuffer sb1 = new StringBuffer();
String eachLine = br1.readLine();
while (eachLine != null)
{
jta2.setForeground(Color.RED);
sb1.append(eachLine);
sb1.append("\n");
eachLine= br1.readLine(); }
jta2.append(sb1.toString());
//input.close(); if(f1.length()==0)
{
jta2.append("Compiled Successfully........\n");
jta2.append("Done........"); } } catch(Exception e)
{ e.printStackTrace(); } }
public void runer(String name)
{
try { jta3.setText("");
String callAndArgs= "cmd /c run.bat "+name;
Process p =Runtime.getRuntime().exec(callAndArgs);
BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream())); String
str=br.readLine(); while(str!=null)
{
System.out.println(str); str=br.readLine();
}
File f1 = new File("output.txt");
FileReader fr = new FileReader(f1);
BufferedReader br1 = new BufferedReader(fr);
StringBuffer sb1 = new StringBuffer();
String eachLine = br1.readLine();
while (eachLine != null)

{
sb1.append(eachLine);
sb1.append("\n");
eachLine = br1.readLine();
}
String sp=sb1.toString();
StringBuffer st=new StringBuffer(sp);
System.out.println(st.length()); int indx=sp.indexOf(">"); int r=1;
while(indx != -1)
{
System.out.println(Integer.toString(indx)+"*");
System.out.println(st);
st.insert(indx+r, "\n");
indx=sp.indexOf(">",indx+1);
r++;
System.out.println(Integer.toString(indx)+"#");
}
jta2.setText(st.toString()); f2.deleteOnExit();
f3.deleteOnExit(); }
catch(Exception e)
{ e.printStackTrace(); } } }
class MyFilter extends javax.swing.filechooser.FileFilter
{
public boolean accept(File file)
{
return file.isDirectory() || file.getName().endsWith(".java");
}
public String getDescription()
{ return "*.java"; } }
/* Test Frame Design */
import javax.swing.*;
import java.awt.*;
public class Test {
public Test() { JFrame f = new JFrame("Test");
f.setLayout(new FlowLayout());
JTextField jt1 = new JTextField(25);
f.add(jt1); f.setVisible(true);
f.setSize(200,200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
new Test();
}
}

OUTPUT:
D:\ Java\jdk1.5.0_03\bin>javac Client.java
D:\ Java\jdk1.5.0_03\bin>javac Test.java
D:\ Java\jdk1.5.0_03\bin>java Test
D:\ Java\jdk1.5.0_03\bin>java Client

Conclusion

S-ar putea să vă placă și