catch(IOException e)
{
System.out.println("Error is"+e);
}
}
}
//FlowLayout demo
/*
public java.awt.FlowLayout();
public java.awt.FlowLayout(int);
public java.awt.FlowLayout(int,int,int);
*/
import java.util.* ;
import java.applet.* ;
import java.awt.*;
//
public class flow extends Applet
{
public void init()
{
String val="java is simple , " +
"awt in java is used " +
"to create GUI";
setLayout(new FlowLayout());
StringTokenizer str=new StringTokenizer(val);
while(str.hasMoreTokens())
add(new Button(str.nextToken()));
}
}
import java.applet.*;
import java.awt.*;
/* */
public class FontDemo extends Applet
{
Font f;
public void init()
{
f=new Font("Bookman old style",Font.BOLD+Font.ITALIC,20);
}
public void paint(Graphics g)
{
g.drawString("This is a demo of default font",50,20);
Font f1=g.getFont();
g.drawString("Font f1="+f1,50,40);
g.drawString("Font family="+f1.getFamily(),50,60);
g.drawString("Font Name="+f1.getFontName(),50,80);
g.drawString("Font Style="+f1.getStyle(),50,100);
g.drawString("Font Size="+f1.getSize(),50,120);
g.setFont(f);
g.drawString("This is a demo of custom font",50,140);
Font f2=g.getFont();
g.drawString("custom Font f2="+f2,50,160);
g.drawString("custom Font family="+f2.getFamily(),50,180);
g.drawString("custom Font Name="+f2.getFontName(),50,200);
g.drawString("custom Font Style="+f2.getStyle(),50,220);
g.drawString("custom Font Size="+f2.getSize(),50,240);
}
}
import java.io.*;
import java.awt.*;
import java.awt.event.*;
/*
*/
public class fontex extends Frame implements MouseListener
{
Label l1;
Font f1,f2;
public fontex()
{
setLayout(null);
l1=new Label("Good Morning");
f1=new Font("Times Roman",Font.BOLD,12);
f2=new Font("Times Roman",Font.BOLD,28);
setSize(800,600);
setVisible(true);
addMouseListener(this);
}
public void mouseEntered(MouseEvent me)
{
l1.setBounds(200,400,400,50);
add(l1);
l1.setFont(f2);
setBackground(Color.yellow);
l1.setBackground(Color.yellow);
l1.setForeground(Color.red);
}
public void mouseExited(MouseEvent me)
{
l1.setBounds(200,400,400,50);
l1.setFont(f1);
setBackground(Color.pink);
l1.setBackground(Color.pink);
l1.setForeground(Color.black);
}
public void mouseClicked(MouseEvent me) { }
public void mousePressed(MouseEvent me) { }
public void mouseReleased(MouseEvent me) { }
public static void main(String ar[])
{
new fontex();
}
}
class For {
public static void main(String[] args) {
int c;
System.out.println("Sebelum for");
for(c=0;c<10 c="" p=""> System.out.println("Nilai c: " + c);
System.out.println("Setelah for");
}
}
Rahul is good boy import java.io.*;
class FOSDemo1
{
public static void main(String s[])
{
try
{char ch='y';
while(ch=='y'|| ch=='Y')
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
FileOutputStream fos=new FileOutputStream("d:/Rahul/xxx/rade.txt");
System.out.println("Enter data to be write");
String str=br.readLine();
byte data[]=str.getBytes();
System.out.println("Writes data in a file");
fos.write(data);
System.out.println("Writin is over\n");
fos.close();
System.out.println("Do u want to continue(y/n)");
ch=(char)br.read();
}
}
catch(IOException e)
{
System.out.println("Error is"+e);
}
}
}
import java.io.*;
class FPwsdemo
{
public static void main(String args[])
{try{
FileWriter fw=new FileWriter("aaa.txt",true);
PrintWriter p=new PrintWriter(fw);
p.println("Hello!");
p.flush();
}catch(Exception e)
{
System.out.println("Error is"+e);
}
}
}//Fig. 11.44: GridLayoutDemo.java
//Testing GridLayoutFrame.
import javax.swing.JFrame;
public class Frame
{
public static void main( String args[] )
{
GridLayoutFrame gridLayoutFrame = new GridLayoutFrame();
gridLayoutFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
gridLayoutFrame.setSize( 300, 200 ); // set frame size
gridLayoutFrame.setVisible( true ); // display frame
} // end main
} // end class GridLayoutDemo
/**************************************************************************
* (C) Copyright 1992-2005 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/
/* Aim : program to create an interface to perform division operations
when user enters the two integers. The division of two values must displayed
in the third text box when user clicks the Cal button . If num1 and num2 are not integers
then the program to throw NumberFormatException.when num1 divide with zero it has to throw
ArithmeticException in exception Message Label.
*/
/* framediv.java */
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class framediv extends JFrame implements ActionListener
{
JPanel p;
JTextField t1,t2,t3;
JButton b;
JLabel msg;
public void actionPerformed(ActionEvent e)
{
int n1,n2,n3;
JButton bt;
bt=(JButton)e.getSource();
if(bt.getLabel().equals("Cal"))
{
try
{
n1=Integer.parseInt(t1.getText());
n2=Integer.parseInt(t2.getText());
n3=n1/n2;
t3.setText(String.valueOf(n3));
msg.setText("Calculation performed......");
}
catch(NumberFormatException ex)
{
msg.setText("Wrong Data Values are enetered...");
}
catch(ArithmeticException ex)
{
msg.setText("Zero divide canot possible");
}
}
}
public framediv()
{
setTitle("Frame for division..");
p=new JPanel();
t1=new JTextField("10000");
t2=new JTextField("1000");
t3=new JTextField("Result Here");
b=new JButton("Cal");
//adding action listener
b.addActionListener(this);
p.add(t1);
p.add(new JLabel(" / "));
p.add(t2);
p.add(new JLabel(" = "));
p.add(t3);
p.add(b);
msg=new JLabel("Click Cal Button to perform cal...");
p.add(msg);
add(p);
setSize(300,400);
setVisible(true);
}
public static void main(String args[])
{
new framediv();
}
}
import java.awt.*;
import java.awt.event.*;
class framelights implements ItemListener
{
Frame f;
Label l;
Checkbox b1,b2,b3;
CheckboxGroup g;
Panel p;
public void itemStateChanged(ItemEvent e)
{
Checkbox c=(Checkbox)e.getSource();
if(c.getLabel().equals("Red"))
{
l.setText("Red color...");
}
else
if(c.getLabel().equals("Yellow"))
{
l.setText("Yellow color...");
}
else
if(c.getLabel().equals("Green"))
{
l.setText("Green color...");
}
}
public framelights()
{
f=new Frame("Frame with Lights");
l=new Label("COLOR BOX.....");
g=new CheckboxGroup();
b1=new Checkbox("Red",g,false);
b2=new Checkbox("Yellow",g,false);
b3=new Checkbox("Green",g,false);
b1.addItemListener(this);
b2.addItemListener(this);
b3.addItemListener(this);
p=new Panel();
p.add(l);
p.add(b1);
p.add(b2);
p.add(b3);
f.add(p);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args)
{
new framelights();
}
}
import java.io.*;
class FRDemo
{
public static void main(String s[])
{
try
{
FileReader fr=new FileReader("d:/curser.txt");
BufferedReader br=new BufferedReader(fr);
String data="";
while((data=br.readLine())!=null)
{
System.out.println(data);
}
fr.close();
System.out.println("Reading is over");
}
catch(IOException e)
{
System.out.println("Error is"+e);
}
}
}
// TO CREATE FRAME
/* public java.awt.Frame();
public java.awt.Frame(java.lang.String); */
import java.awt.* ;
import java.applet.*;
//
public class frm
{
public static void main(String [] s)
{
Frame f=new Frame("frame in java");
f.resize(100,100);
f.setBackground(Color.red);
f.setVisible(true); //or f.show() ;
}
}
//to run c:>java frm
import java.io.*;
class Frsdemo
{
public static void main(String args[])
{
try
{
FileReader frs= new FileReader("Frsdemo.java ");
BufferedReader br=new BufferedReader(frs);
String str="";
while((str=br.readLine())!=null)
{
System.out.println(str);
}
frs.close();
System.out.println("Reading is over");
}
catch(IOException ie)
{
System.out.println("Error is" +ie);
}
}
} import java.io.*;
class FWDemo
{
public static void main(String s[])
{
try
{
char ch='y';
while(ch=='y'|| ch=='Y')
{
FileWriter fw=new FileWriter("d:/Rahul/priyam.txt",true);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter data to be write");
String data=br.readLine();
fw.write(data);
System.out.println("Writing is over \nDo u want to continue");
ch=(char)br.read();
fw.close();
}
}
catch(IOException e)
{
System.out.println("Error is"+e);
}
}
}
import java.io.*;
class Fwsdemo
{
public static void main(String args[])
{
try
{
FileWriter fws= new FileWriter("aaa.txt ",true);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str=br.readLine();
fws.write(str+"\n");
fws.close();
System.out.println("Writing is over");
}
catch(IOException ie)
{
System.out.println("Error is" +ie);
}
}
}import java.io.*;
class geometry
{
public geometry()
{
int length;
int bredth;
int height;
int radius;
int aos; //area of square
int aor; //area of rectangle
int voc; //volume of cube
int vocd; // volume of cuboid
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
}
int areaOfSquare(int l)
{
aos = l*l;
}
int areaOfRect(int l, int b)
{
aor = l*b;
}
int volumeOfCube(int l)
{
voc = l*l*l;
}
int volumeOfCuboid(int l, int b, int h)
{
vocd = l*b*h;
}
public static void main(String[] args)
{
geometry g1 = new geometry();
}
}import java.applet.*;
import java.awt.*;
/* */
public class GR extends Applet
{
int x=30; int y=30;
public void paint(Graphics g)
{
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
Font flist[]=ge.getAllFonts();
for(int i=0;i<=flist.length;i++)
{
g.drawString(flist[i], x,y);
y=y+15;
if(y>=599)
{
x=x+200;
y=30;
}}
}
}
import javax.swing.JOptionPane;
public class GradePerSubjects
{
public static void main(String[] args)
{
Double Activity,Quiz,Attendance,Assignment,Exam,Grade;
Activity=Double.parseDouble(JOptionPane.showInputDialog("Enter partial Grade for Activity "));
Quiz=Double.parseDouble(JOptionPane.showInputDialog("Enter partial Grade for Quiz "));
Attendance=Double.parseDouble(JOptionPane.showInputDialog("Enter partial Grade for Attendance "));
Assignment=Double.parseDouble(JOptionPane.showInputDialog("Enter partial Grade for Assignment "));
Exam=Double.parseDouble(JOptionPane.showInputDialog("Enter partial Grade for Exam "));
Grade=((Activity*0.15)+(Quiz*0.15)+(Attendance*0.10)+(Assignment*0.10)+(Exam*0.5));
JOptionPane.showMessageDialog(null,"Your grade for this subject is "+Grade);
}
}
import java.awt.*;
import java.applet.*;
/*
public class GraphicsApplet extends Applet
{
public void paint(Graphics g)
{
/*g.drawRect(100,150,300,300);
g.drawRect(100,150,25,50);
g.drawRect(100,150,50,50);
g.drawRect(100,150,75,50);
g.drawRect(325,150,25,50);
g.drawRect(325,150,50,50);
g.drawRect(325,150,75,50);
g.drawRect(225,300,50,150);
g.drawLine(100,150,250,75);
g.drawLine(250,75,400,150);
g.drawLine(100,150,250,75);
g.drawLine(250,75,250,25);
g.drawRect(250,25,40,20);
g.drawOval(260,25,20,20);
g.drawLine(225,450,175,500);
g.drawLine(275,450,175,550);
int j=100;
for(int i=10;i<=50;i=i+10)
{
g.drawRect(i,i,j-2*i,j-2*i);
}
g.drawArc(50,50,400,300,0,-90);
g.fillArc(50,50,400,300,0,-90);
int x[]={225,150,150,225,300,300};
int y[]={50,150,300,400,300,150};
//g.setColor(Color.white);
setForeground(Color.red);
g.drawPolygon(x,y,6);
//g.setColor(Color.red);
setBackground(Color.GREEN);*/
g.drawOval(100,100,175,200);
}
}import java.awt.*;
import java.applet.*;
/**/
public class GraphicsDemo extends Applet
{
public void paint(Graphics g)
{
g.drawLine(50,50,150,50);
g.drawLine(50,50,50,100);
g.drawLine(50,100,150,100);
g.drawLine(150,100,150,50);
g.drawRect(200,200,100,50);
g.drawRect(50,200,100,50);
g.drawRect(200,50,100,50);
g.fillRect(200,200,100,50);
g.drawOval(50,200,100,50);
g.drawOval(200,50,100,50);
g.drawOval(120,120,50,50);
g.drawArc(120,120,50,50,0,90);
}
}import java.applet.*;
import java.awt.*;
/**/
public class GraphicsHome extends Applet
{
public void paint(Graphics g)
{
g.drawRect(200,250,400,300);
g.drawLine(200,250,400,100);
g.drawLine(600,250,400,100);
g.drawLine(400,100,400,50);
g.drawRect(400,50,35,25);
g.drawOval(410,50,10,25);
g.drawRect(300,350,200,200);
g.drawRect(200,250,80,80);
g.drawLine(220,250,220,330);
g.drawLine(240,250,240,330);
g.drawLine(260,250,260,330);
g.drawRect(520,250,80,80);
g.drawLine(540,250,540,330);
g.drawLine(560,250,56=0,330);
g.drawLine(580,250,580,330);
}
}
//gridLayout demo
/*
Compiled from GridLayout.java
public class java.awt.GridLayout extends java.lang.Object implements java.awt.LayoutManager, java.io.Serializable {
int hgap;
int vgap;
int rows;
int cols;
public java.awt.GridLayout();
public java.awt.GridLayout(int,int);
public java.awt.GridLayout(int,int,int,int);
*/
import java.awt.*;
import java.applet.* ;
//
public class GridLayoutDemo extends Applet
{
public void init()
{
Button b1,b2,b3,b4;
setLayout(new GridLayout(4,4));
b1=new Button("Button ONE");
b2=new Button("Button TWO");
b3=new Button("Button THREE");
b4=new Button("Button FOUR");
add(b1);add(b2);add(b3);add(b4);
GridLayoutDemo d=new GridLayoutDemo();
d.setVisible(true);
}
}
import java.sql.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class GUIDisplay extends JFrame implements ActionListener
{
JPanel mp,p1,p2,p3;
JLabel l1,l2;
JButton b1;
JTextField t1,t2;
Connection con;
Statement st;
GUIDisplay()
{
l1=new JLabel("ID :-");
l2=new JLabel("Name :-");
t1=new JTextField(10);
t2=new JTextField(10);
b1=new JButton("Insert");
b1.addActionListener(this);
p1=new JPanel(); p1.add(l1); p1.add(t1);
p2=new JPanel(); p2.add(l2); p2.add(t2);
p3=new JPanel(); p3.add(b1);
mp=new JPanel(new GridLayout(3,1)); mp.add(p1); mp.add(p2); mp.add(p3);
Container ct=getContentPane();
ct.add(mp);
setTitle("GUI Display");
setSize(500,500);
setVisible(true);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:stud_ash");
String title="Plain dialog";
String msg="Data Base Connected";
int msgtype=JOptionPane.PLAIN_MESSAGE;
JOptionPane.showMessageDialog(this,msg,title,msgtype);
}catch(Exception e)
{
System.out.println("Error is"+e);
}
}
public void actionPerformed(ActionEvent ae)
{
try
{
int id=Integer.parseInt(t1.getText());
String nm=t2.getText();
st=con.createStatement();
String query="insert into studx values("+id+",' "+nm+" ')";
st.executeUpdate(query);
String title="Plain dialog";
String msg="Record Inserted";
int msgtype=JOptionPane.PLAIN_MESSAGE;
JOptionPane.showMessageDialog(this,msg,title,msgtype);
st.close();
con.close();
}catch(Exception e)
{
System.out.println("Error is"+e);
}
}
public static void main(String arg[])
{
new GUIDisplay();
}
}import java.sql.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class GUIDisplayPst extends JFrame implements ActionListener
{
JPanel mp,p1,p2,p3,p4;
JLabel l1,l2;
JButton b1,bc,bf,bn,bp,bl;
JTextField t1,t2;
Connection con;
PreparedStatement pst;
ResultSet rs;
GUIDisplayPst()
{
l1=new JLabel("ID :-");
l2=new JLabel("Name :-");
t1=new JTextField(10);
t2=new JTextField(10);
b1=new JButton("Insert");
b1.addActionListener(this);
bc=new JButton("Clear");
bc.addActionListener(this);
bf=new JButton("First");
bf.addActionListener(this);
bn=new JButton("Next");
bn.addActionListener(this);
bp=new JButton("Previous");
bp.addActionListener(this);
bl=new JButton("Last");
bl.addActionListener(this);
p1=new JPanel(); p1.add(l1); p1.add(t1);
p2=new JPanel(); p2.add(l2); p2.add(t2);
p3=new JPanel(); p3.add(b1);
p4=new JPanel(); p4.add(bf); p4.add(bn); p4.add(bp); p4.add(bl);
mp=new JPanel(new GridLayout(3,1)); mp.add(p1); mp.add(p2); mp.add(p3);
Container ct=getContentPane();
ct.add(mp);
setTitle("GUI Display");
setSize(300,400);
setVisible(true);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:stud_ash");
JOptionPane.showMessageDialog(this,"Data Base Connected");
int rsid=ResultSet.CONCUR_READ_ONLY;
int rsnm= ResultSet.CONCUR_READ_ONLY;
}catch(Exception e)
{
System.out.println("Error is"+e);
}
}
public void actionPerformed(ActionEvent ae)
{
try
{
if(ae.getSource()==bf)
{
rs.first();
display();
}
if(ae.getSource()==bn)
{
if(rs.next())
{
display();
}
else
{
JOptionPane.showMessageDialog(this,"No more records");
}
}
if(ae.getSource()==bp)
{
if(rs.previous())
{
display();
}
else
{
JOptionPane.showMessageDialog(this,"No previous records");
}
}
if(ae.getSource()==bl)
{
rs.last();
display();
}
if(ae.getSource()==b1)
{
int id=Integer.parseInt(t1.getText());
String nm=t2.getText();
pst=con.prepareStatement("insert into studx values(?,?)");
pst.setInt(1,id);
pst.setString(2,nm);
pst.executeUpdate();
JOptionPane.showMessageDialog(this,"Record Inserted");
pst.close();
}
con.close();
}catch(Exception e)
{
System.out.println("Error is"+e);
}
}
public static void main(String arg[])
{
new GUIDisplayPst();
}
public void display()
{
t1.setText(""+rs.getInt(1));
t2.setText(""+rs.getString(2));
}
}import java.awt.* ;
import java.applet.*;
public class hell extends Applet {
public void paint(Graphics g) {
g.drawString("Welcome to Java Applets",20,20); } } public class hello{
public static void main (String[] args){
System.out.println("Selamat Datang di Ilmu Komputer UGM");
}
}
// The package containing our stubs.
import HelloApp.*;
// HelloClient will use the naming service.
import org.omg.CosNaming.*;
// The package containing special exceptions thrown by the name service.
import org.omg.CosNaming.NamingContextPackage.*;
// All CORBA applications need these classes.
import org.omg.CORBA.*;
// Needed for the applet.
import java.awt.Graphics;
public class HelloApplet extends java.applet.Applet
{
public void init()
{
try{
// Create and initialize the ORB
ORB orb = ORB.init(this, null);
// Get the root naming context
org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService");
NamingContext ncRef = NamingContextHelper.narrow(objRef);
// Resolve the object reference in naming
NameComponent nc = new NameComponent("Hello", "");
NameComponent path[] = {nc};
Hello helloRef = HelloHelper.narrow(ncRef.resolve(path));
// Call the Hello server object and print the results
message = helloRef.sayHello();
} catch(Exception e) {
System.out.println("HelloApplet exception: " + e);
e.printStackTrace(System.out);
}
}
String message = "";
public void paint(Graphics g)
{
g.drawString(message, 25, 50);
}
}
class Hello {
public static void main(String args[]) {
System.out.println("\n " + args[0] + "\n " + args[1]);
}
}
public class HelloWorld {
public static void main (String args[]) {
System.out.println("\n Hello, New World!");
}
}
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* $Id$
*
*/
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* The simplest possible servlet.
*
* @author James Duncan Davidson
*/
public class HelloWorldExample extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
ResourceBundle rb =
ResourceBundle.getBundle("LocalStrings",request.getLocale());
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println("");
String title = rb.getString("helloworld.title");
out.println("
out.println("10>
"); out.println("");
// note that all links are created to be relative. this
// ensures that we can move the web application that this
// servlet belongs to to a different place in the url
// tree and not have any harmful side effects.
// XXX
// making these absolute till we work out the
// addition of a PathInfo issue
out.println("");
out.println(" "width=24 align=right border=0 alt=\"view code\">
"); out.println("");
out.println(" "width=24 align=right border=0 alt=\"return\">
"); out.println("
" + title + "
");out.println("
"); out.println("
"); }
}
public class HellWorld{
public static void main(String[] args){
System.out.println("Hello World");
}
}/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package util;
/**
* HTML filter utility.
*
* @author Craig R. McClanahan
* @author Tim Tye
* @version $Revision$ $Date$
*/
public final class HTMLFilter {
/**
* Filter the specified message string for characters that are sensitive
* in HTML. This avoids potential attacks caused by including JavaScript
* codes in the request URL that is often reported in error messages.
*
* @param message The message string to be filtered
*/
public static String filter(String message) {
if (message == null)
return (null);
char content[] = new char[message.length()];
message.getChars(0, message.length(), content, 0);
StringBuffer result = new StringBuffer(content.length + 50);
for (int i = 0; i < content.length; i++) {
switch (content[i]) {
case '<':
result.append("<");
break;
case '>':
result.append(">");
break;
case '&':
result.append("&");
break;
case '"':
result.append(""");
break;
default:
result.append(content[i]);
}
}
return (result.toString());
}
}
import java.io.*;
interface weightage
{
int sports;
}
class student
{
import java.applet.*;
import java.awt.*;
/* */
public class ImgApplet extends Applet
{
Image img;
public void init()
{
img=getImage(getCodeBase(),"Sunset.jpg");
}
public void paint(Graphics g)
{
g.drawImage(img,50,50,20,20,this);
}
}
class IncrementDecrement{
public static void main (String[] args){
int i = 1;
System.out.println("i : " + i);
System.out.println("++i : " + ++i);
System.out.println("i++ : " + i++);
System.out.println("i : " + i);
System.out.println("--i : " + --i);
System.out.println("i-- : " + i--);
System.out.println("i : " + i);
}
}
// Demonstrate InetAddress.
import java.net.*;
class Inet
{
public static void main(String args[]) throws UnknownHostException {
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("localhost");
System.out.println(Address);
InetAddress SW[] = InetAddress.getAllByName("localhost");
for (int i=0; i
}
}
// Demonstrate InetAddress.
import java.net.*;
import java.io.*;
class Inet1
{
public static void main(String args[]) throws UnknownHostException,IOException {
System.out.println("Enter the host name :");
String s = new DataInputStream(System.in).readLine();
InetAddress SW = InetAddress.getByName(s);
System.out.println(SW);
}
}
import java.net.*;
class InetDemo
{
public static void main(String arg[])
{
try
{
InetAddress local=InetAddress.getLocalHost();
System.out.println("Ip address of local pc="+local);
InetAddress remote =InetAddress.getByName("fileserver");
System.out.println("ip address of remoten pc i.e. fileserver ip="+remote);
}
catch(UnknownHostException e)
{ System.out.println("error is DNS"+e);
}
}
}class A {
int x;
int y;
void TampilkanNilaixy() {
System.out.println("Nilai x : " + x + ", y : " + y);
}
}
class B extends A {
int z;
void TampilkanJumlah() {
//subclass dapat mengakses member dari superclass
System.out.println("Jumlah : " + (x+y+z));
}
}
class Inheritance {
public static void main(String[] args) {
A VarsuperOb = new A();
B VarsubOb = new B();
System.out.println("SuperClass");
VarsuperOb.x = 10;
VarsuperOb.y = 20;
VarsuperOb.TampilkanNilaixy();
System.out.println("SubClass");
//member superclass dapat diakses dari subclass nya
VarsubOb.x = 5;
VarsubOb.y = 4;
VarsubOb.TampilkanNilaixy();
System.out.println("SubClass Jumlah");
//member tambahan yang hanya ada dalam subclass
VarsubOb.z = 30;
VarsubOb.TampilkanJumlah();
System.out.println("SubClass");
VarsubOb.x = 15;
VarsubOb.y = 14;
VarsubOb.TampilkanNilaixy();
System.out.println("SuperClass");
VarsuperOb.x = 10;
VarsuperOb.y = 20;
//super.x = 100; error
//super.y = 200; error
VarsuperOb.TampilkanNilaixy();
System.out.println("SubClass Jumlah");
VarsubOb.z = 60;
VarsubOb.TampilkanJumlah();
}
}class InheritInterfaceDemo implements SubInterface,SuperInterface1
{
public void add(int a,int b)
{
int c=a+b;
System.out.println("Addition of "+a+" and "+b+" is "+c);
}
public void sub(int a,int b)
{
int c=a-b;
System.out.println("Substraction of "+a+" and "+b+" is "+c);
}
public void mul(int a,int b)
{
int c=a*b;
System.out.println("Multiplication of "+a+" and "+b+" is "+c);
}
public static void main(String s[])
{
InheritInterfaceDemo obj=new InheritInterfaceDemo();
obj.add(50,4);
obj.sub(10,4);
obj.mul(4,5);
}
}import java.io.*;
class InputStream {
public static void main(String[] args) throws IOException {
byte[] data = new byte[10];
System.out.print("Ketik 10 buah karakter :");
System.in.read(data);
System.out.print("Karakter yang Anda ketik yaitu : ");
for(int i=0;i System.out.print((char)data[i]);
System.out.print(data[i]);
}
}
}import java.util.*;
import java.io.*;
public class integrate
{
public static void main(String[] args) throws Exception
{
ArrayList allIndexList= new ArrayList();// id for data for all files
File iff=new File("iris.data");
FileInputStream ifis=new FileInputStream (iff);
InputStreamReader iisr=new InputStreamReader(ifis);
BufferedReader ibr=new BufferedReader(iisr);
int count=0;
String strr=ibr.readLine();
while ( strr != null )
{
count++;
strr=ibr.readLine();
}
ibr.close();
System.out.println(count);
/* ****** READING A DATA FROM PARTITIONS ************ */
System.out.print("Please input the file name: ");
InputStreamReader isrr = new InputStreamReader(System.in);
BufferedReader buff = new BufferedReader(isrr);
String ifilename = buff.readLine();
for (int i=1; i<=8;i++)
{
ArrayList indexList=new ArrayList();// id for the data in each files
String filename=ifilename + i +".rsl" ;
FileInputStream fis=new FileInputStream(filename);
InputStreamReader isr= new InputStreamReader(fis);
BufferedReader br=new BufferedReader(isr);
String str;
while ( (str=br.readLine()) != null )
{
StringTokenizer st=new StringTokenizer(str,",");
Integer index= new Integer( st.nextToken());
indexList.add(index);
}
//System.out.println(indexList.size());
allIndexList.add(indexList);
br.close();
}
//System.out.println(allIndexList);
/*------------ calculating co-association matrix --------------------------*/
double [][]coAssoc=new double[count][count];
for(int i=0;i
//System.out.println(allIndexList.size());// number of the clusters
int R=3;
for (int clusterID=0; clusterID
ArrayList al= (ArrayList)allIndexList.get(clusterID);
int alength=al.size();//each cluster size
for ( int i=0; i < alength; i++)
{
int indexi=((Integer)al.get(i)).intValue();
for ( int j=i+1; j < alength; j++)
{
int indexj=((Integer)al.get(j)).intValue();
coAssoc[indexi][indexj]= coAssoc[indexi][indexj] + (1.0/R);
}
}
}
/*
for(int i=0;i
/*-------------------- clustering----------------------------*/
int cluster=0;
int ac[]=new int[count];
for(int i=0; i
double val;
int maxc,minc;
for(int i=0;i
for(int j=0;j
if (i!= j)
{
if (i < j)
{
val=coAssoc[i][j];
if (val > 0.5)
{
if (( ac[i]== -1) && ( ac[j] == -1)) //Not assigned cluster so far
{
ac[i]=cluster;
ac[j]=cluster;
cluster++;
}
else if (( ac[i] != -1) && ( ac[j] != -1)) // both assigned cluster already
{
int c1= ac[i];
int c2= ac[j];
if (c1!=c2) // Not in same cluster merge them
{
if (c1 < c2)
{
maxc=c2;
minc=c1;
}
else
{
maxc=c1;
minc=c2;
}
for(int k=0; k<150 k="" p=""> {
if (ac[k]== maxc)
ac[k]=minc;
else
{
if ( (ac[k] != 0) && (ac[k] != -1))
{
if (ac[k] >=maxc)
{
ac[k]=ac[k]-1;
}
}
}
}
if ( (cluster != 0) && (cluster != -1))
cluster--;
}
}
else if (ac[i] == -1) // i not assigned cluster so far
{
ac[i]=ac[j];
}
else if (ac[j] == -1) // j not assigned cluster so far
{
ac[j]=ac[i];
}
} // if val> 0.5
}
}
}// for j
}
// cluster++;
//System.out.println(cluster);
int csize;
int tot=0;
for (int c=0;c
csize=0;
System.out.println("\nCLUSTER "+c +"\n");
for(int i=0; i
{
System.out.print(i + " ");
csize++;
}
System.out.println("\nCLUSTER "+ c + "Size " + csize + "\n");
tot +=csize;
}
if(tot < count)
{
System.out.println("\nCLUSTER " + cluster);
for (int i=0;i
if (ac[i] == -1)
{
System.out.print(i + " ");
ac[i]=cluster;
}
}
cluster++;
}
//write to files
for ( int c=0;c
File f=new File("out"+c+".rsl");
FileOutputStream fos=new FileOutputStream (f);
PrintStream ps=new PrintStream(fos);
FileInputStream fis=new FileInputStream("iris.data");
InputStreamReader isr= new InputStreamReader(fis);
BufferedReader br=new BufferedReader(isr);
String str;
for(int i=0;i
str=br.readLine();
if (ac[i]==c)
ps.println(str);
}
br.close();
ps.close();
}
System.out.println("\nCLUSTER " + cluster);
} // main
}//classinterface Control {
public void pindahChannel(int channel);
public void PerbesarVolume(int intensitas);
public void PerkecilVolume(int intensitas);
}
class TelevisiA implements Control {
String[] channelTv = {"RCTI","SCTV","INDOSIAR","TRANS TV","TPI"};
public void pindahChannel(int channel) {
System.out.println("Pindah channel pada tv A ke : " + channelTv[channel]);
}
public void PerbesarVolume(int intensitas) {
System.out.println("Perbesar intensitas volume pada tv A sebanyak : " + intensitas);
}
public void PerkecilVolume(int intensitas) {
System.out.println("Perkecil intensitas volume pada tv A sebanyak : " + intensitas);
}
}
class TelevisiB implements Control {
String[] chanTv = {"TVRI","LA TV","TV 7","RCTI","SCTV"};
public void pindahChannel(int channel) {
System.out.println("Perintah pindah channel pada tv B ke : " + chanTv[channel]);
}
public void PerbesarVolume(int intensitas) {
System.out.println("Perbesar intensitas volume pada tv B sebanyak : " + intensitas);
}
public void PerkecilVolume(int intensitas) {
System.out.println("Perkecil intensitas volume pada tv B sebanyak : " + intensitas);
}
}
class RemoteControl {
public static final int PINDAH_CHANNEL = 1;
public static final int PERBESAR_VOLUME = 2;
public static final int PERKECIL_VOLUME = 3;
public void kirimPerintahKeTv(int aksi,Control tv,int tombol) {
switch(aksi) {
case PINDAH_CHANNEL:
tv.pindahChannel(tombol);
break;
case PERBESAR_VOLUME:
tv.PerbesarVolume(tombol);
break;
case PERKECIL_VOLUME:
tv.PerkecilVolume(tombol);
}
}
}
class Interface {
public static void main(String[] args) {
TelevisiA tvA = new TelevisiA();
TelevisiB tvB = new TelevisiB();
RemoteControl rc = new RemoteControl();
//Kirim perintah ke tvA
rc.kirimPerintahKeTv(RemoteControl.PINDAH_CHANNEL,tvA,2);
rc.kirimPerintahKeTv(RemoteControl.PERBESAR_VOLUME,tvA,5);
//Kirim perintah ke tvB
rc.kirimPerintahKeTv(RemoteControl.PINDAH_CHANNEL,tvB,1);
rc.kirimPerintahKeTv(RemoteControl.PERKECIL_VOLUME,tvB,3);
}
}public interface InterfaceCube
{
void cube(int n);
}
interface InterfaceDemo
{
int x=10;
void Square(int n);
}
class InterfaceImpl implements InterfaceDemo
{
public void Square(int n)
{
int s=n*n;
System.out.println("Sqaure of"+n+"is="+s);
}
public static void main(String args[])
{
InterfaceImpl j=new InterfaceImpl();
j.Square(x);
}
}
interface InterfaceDemo
{
int x=10;
void Square(int n);
}
class InterfaceImpl1 implements InterfaceDemo
{
public void Square(int n)
{
int s=n*n;
System.out.println("Sqaure of"+n+"is="+s);
}
public void cube(int n)
{
int c=n*n*n;
System.out.println("Cube of"+n+"is="+c);
}
public static void main(String args[])
{
InterfaceImpl1 j=new InterfaceImpl1();
j.Square(x);
j.cube(5);
}
}
interface InterfaceDemo
{
int x=10;
void Square(int n);
}
interface InterfaceCube
{
void cube(int n);
}
class InterfaceImpl2 implements InterfaceDemo,InterfaceCube
{
public void Square(int n)
{
int s=n*n;
System.out.println("Sqaure of"+n+"is="+s);
}
public void cube(int n)
{
int c=n*n*n;
System.out.println("Cube of"+n+"is="+c);
}
public static void main(String args[])
{
InterfaceImpl2 j=new InterfaceImpl2();
j.Square(x);
j.cube(x);
}
}
class InterfaceImpl3 implements InterfaceSub
{
public void Add(int a,int b)
{
int s=a+b;
System.out.println("Addtion of a & b is="+s);
}
public void Sub(int a,int b)
{
int c=a-b;
System.out.println("Substration of a & b is="+c);
}
public static void main(String args[])
{
InterfaceImpl3 j=new InterfaceImpl3();
j.Add(10,20);
j.Sub(30,20);
}
}
interface InterfaceAdd
{
void Add(int a,int b);
}
public interface InterfaceSub extends InterfaceAdd
{
void Sub(int a,int b);
}
import java.io.*;
class intopost
{
int top,j,i;
String str;
char t,postfix[],s[];
public intopost()
{
top=-1;i=0;j=0;
postfix=new char[30];
s=new char[30];
}
public void push(char t)
{
top++;
s[top]=t;
}
public char pop()
{
char t;
t=s[top];
top--;
return t;
}
public void check()
{
while(priority(t)<=priority(s[top]))
postfix[j++]=pop();
}
int priority(char t)
{
if(t=='^')
return 4;
else
if(t=='*')
return 3;
else
if(t=='/')
return 2;
else
if(t=='+' || t=='-')
return 1;
else
return 0;
}
public void convert(String str)
{
push('#');
while(i
t=str.charAt(i);
if( (t>='a' && t<='z') || (t>='A' && t<='Z'))
postfix[j++]=t;
else
{
if(t=='+' || t=='-' || t=='*' || t=='/' || t=='(' || t==')' || t=='^')
{
switch(t)
{
case '+':
case '-':
check();
push(t);
break;
case '*':
case '/':
check();
push(t);
break;
case '(':
push(t);
break;
case '^':
check();
push(t);
break;
case ')':
do
{
t=pop();
postfix[j++]=t;
}while(t!='(');
j--;
break;
}
}
}
i++;
}
while(s[top]!='#')
postfix[j++]=pop();
postfix[j]='\0';
System.out.println(postfix);
}
public static void main(String args[]) throws IOException
{
String str;
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter a string?");
str=in.readLine();
(new intopost()).convert(str);
}
}
import java.io.*;
class item
{
int icode,qty,up,total;
String iname;
void getdata()throws IOException
{
DataInputStream in = new DataInputStream(System.in);
System.out.print("enter the item code\t:");
icode = Integer.parseInt(in.readLine());
System.out.print("enter the item name\t:");
iname = in.readLine();
System.out.print("enter the qty\t:");
qty = Integer.parseInt(in.readLine());
System.out.print("enter the unit price\t:");
up = Integer.parseInt(in.readLine());
}
void cal()
{
total = qty*up;
System.out.println("Total amount is\t:"+total);
}
}
class item1
{
public static void main(String args[])throws IOException
{
item I = new item();
I.getdata();
I.cal();
}
}import java.io.*;
import java.lang.*;
class item
{
int icode,total;
void getdata()
{
try
{
DataInputStream in = new DataInputStream(System.in);
System.out.print("enter the item code\t:");
icode = Integer.parseInt(in.readLine());
System.out.print("enter the total\t:");
total = Integer.parseInt(in.readLine());
}
catch(IOException e)
{
System.out.println("input Failure");
}
catch(NumberFormatException e)
{
System.out.println("THE DATA IS WRONG");
}
finally
{
System.out.println("PROGRAM END");
}
}
}
class item11
{
public static void main(String args[])
{
try
{
item I = new item();
I.getdata();
}
catch(NullPointerException e)
{
System.out.println("array of object to pass the constructor");
}
}
}import java.sql.*;
public class JdbcAccess
{
Connection con;
Statement st;
public JdbcAccess()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:stud_ash");
System.out.println("Data base is created");
st=con.createStatement();
String query="create table studx(id number, name text)";
st.executeUpdate(query);
System.out.println("Table is created successfully2");
}catch(Exception e)
{
System.out.println("Error is"+e);
}
}
public static void main(String arg[])
{
new JdbcAccess();
}
}import java.sql.*;
public class JdbcAccessCreate
{
Connection con;
Statement st;
public JdbcAccessCreate()
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:abc");
System.out.println("Database Connected");
st=con.createStatement();
String query="create table student(roll number,name text,contactno number)";
st.executeUpdate(query);
System.out.println("Table created successfully");
}catch(Exception e)
{
System.out.println("Error in connection"+e);
}
}
public static void main(String arg[])
{
new JdbcAccessCreate();
}
}
import java.sql.*;
public class JdbcAccessInsert
{
Connection con;
Statement st;
public JdbcAccessInsert()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:stud_ash");
System.out.println("Data base is created");
st=con.createStatement();
String query="insert into studx values (101,'Lince')";
st.executeUpdate(query);
System.out.println("Record successfully inserted");
st.close();
con.close();
}catch(Exception e)
{
System.out.println("Error is"+e);
}
}
public static void main(String arg[])
{
new JdbcAccessInsert();
}
}import java.sql.*;
import java.io.*;
public class JdbcAccessUInput
{
Connection con;
Statement st;
BufferedReader br;
public JdbcAccessUInput()
{
try
{
// char ch='y';
// while(ch=='y' || ch=='Y')
// {
// br=new BufferedReader(new InputStreamReader(System.in));
// System.out.println("Enter id");
// int id=Integer.parseInt(br.readLine());
// System.out.println("Enter name");
// String nm=br.readLine();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:stud_ash");
System.out.println("Data base is created");
st=con.createStatement();
String query="update studx set id=107 where id=121";
st.executeUpdate(query);
st.close();
con.close();
System.out.println("Record successfully inserted \n Do you wish to insert more records?");
// ch=(char)br.read();
//}
}catch(Exception e)
{
System.out.println("Error is"+e);
}
}
public static void main(String arg[])
{
new JdbcAccessUInput();
}
}import java.sql.*;
import java.io.*;
public class JdbcAccessUInput1
{
Connection con;
PreparedStatement pst;
Statement st;
BufferedReader br;
ResultSet rs;
public JdbcAccessUInput1()
{
try
{
char ch='y';
while(ch=='y' || ch=='Y')
{
br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter id");
int id=Integer.parseInt(br.readLine());
System.out.println("Enter name");
String nm=br.readLine();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:stud_ash");
System.out.println("Data base is created");
pst=con.prepareStatement("insert into studx values(?,?)");
pst.setInt(1,id);
pst.setString(2,nm);
pst.executeUpdate();
pst.close();
System.out.println("Record successfully inserted \n Do you wish to insert more records?");
ch=(char)br.read();
}
st=con.createStatement();
String query="Select * from studx";
rs=st.executeQuery(query);
System.out.println(" Record Detials are :- \n Id \t Name ");
while(rs.next())
{
System.out.println(rs.getInt(1)+"\t"+rs.getString(2));
}
con.close();
}catch(Exception e)
{
System.out.println("Error is"+e);
}
}
public static void main(String arg[])
{
new JdbcAccessUInput1();
}
}import java.sql.*;
public class JdbcOracle
{
Connection con;
Statement st;
public JdbcOracle()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:stud_ash1","abc","abc");
System.out.println("databace is created");
st=con.createStatement();
String query="create table xstud (id number(3), name varchar2(20));";
st.executeUpdate(query);
System.out.println("Table is created successfully2");
}catch(Exception e)
{
System.out.println("Error is"+e);
}
}
public static void main(String arg[])
{
new JdbcOracle();
}
}import java.sql.*;
public class JdbcOracleCreate
{
Connection con;
Statement st;
public JdbcOracleCreate()
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:abc","scott","tiger");
System.out.println("Database Connected");
st=con.createStatement();
String query="create table student_xx(roll number(4),name varchar2(20),contactno number(10))";
st.executeUpdate(query);
System.out.println("Table created successfully");
}catch(Exception e)
{
System.out.println("Error in connection"+e);
}
}
public static void main(String arg[])
{
new JdbcOracleCreate();
}
}
import java.sql.*;
public class JdbcOracleInsert
{
Connection con;
Statement st;
public JdbcOracleInsert()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:stud_ash1","abc","abc");
System.out.println("Data base is created");
st=con.createStatement();
String query="insert into xstud values (101,'Lince')";
st.executeUpdate(query);
System.out.println("Record successfully inserted");
}catch(Exception e)
{
System.out.println("Error is"+e);
}
}
public static void main(String arg[])
{
new JdbcOracleInsert();
}
}import java.sql.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
public class JdbcOracleInsertJF extends JFrame implements ActionListener
{
Connection con;
int r,ct1;
String nm;
PreparedStatement pst;
JLabel l1,l2,l3;
JTextField t1,t2,t3;
JButton b;
JPanel p,p1,mp;
public JdbcOracleInsertJF()
{
l1=new JLabel("Roll");
l2=new JLabel("Name");
l3=new JLabel("DOB");
t1=new JTextField(20);
t2=new JTextField(20);
t3=new JTextField(20);
b=new JButton("Insert");
b.addActionListener(this);
p=new JPanel(new GridLayout(3,2));
p.add(l1);
p.add(t1);
p.add(l2);
p.add(t2);
p.add(l3);
p.add(t3);
p1=new JPanel();
p1.add(b);
mp=new JPanel(new GridLayout(2,1));
mp.add(p);
mp.add(p1);
Container ct=getContentPane();
ct.setLayout(new FlowLayout());
ct.add(mp);
setTitle("Demo");
setSize(400,400);
setVisible(true);
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:abc","scott","tiger");
JOptionPane.showMessageDialog(this,"Database Connected");
pst=con.prepareStatement("insert into student_xx values(?,?,?)");
}catch(Exception e)
{
System.out.println("Error in connection"+e);
}
}
public void actionPerformed(ActionEvent ae)
{
try{
r=Integer.parseInt(t1.getText());
nm=t2.getText();
ct1=Integer.parseInt(t3.getText());
pst.setInt(1,r);
pst.setString(2,nm);
pst.setInt(3,ct1);
pst.executeUpdate();
JOptionPane.showMessageDialog(this,"Record inserted ");
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error is "+e);
}
}
public static void main(String arg[])
{
new JdbcOracleInsertJF();
}
}
import java.sql.*;
public class JdbcOracleSelect
{
Connection con;
Statement st;
ResultSet rs;
public JdbcOracleSelect()
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:abc","scott","tiger");
System.out.println("Database Connected");
st=con.createStatement();
String query="select * from stud_ash";
rs=st.executeQuery(query);
System.out.println("Roll \t Name \t Cont No.");
while(rs.next())
{
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));
}
}catch(Exception e)
{
System.out.println("Error in connection"+e);
}
}
public static void main(String arg[])
{
new JdbcOracleSelect();
}
}
import java.sql.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
import java.util.*;
public class JdbcOracleSelectAll extends JFrame implements ActionListener
{
Connection con;
ResultSet rs;
Statement st;
ResultSetMetaData rsmd;
JLabel l1,l2;
JTable jtab;
JScrollPane jsp;
JTextField t1;
JButton b_execute;
JPanel p1,p2,mp;
Vector head,row,data;
public JdbcOracleSelectAll()
{
l1=new JLabel("SQL");
l2=new JLabel("Details are");
t1=new JTextField(20);
b_execute=new JButton("Execute");
b_execute.addActionListener(this);
p1=new JPanel();
jtab=new JTable();
int vsp=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
int hsp=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
jsp=new JScrollPane(jtab,vsp,hsp);
p1.add(l1);
p1.add(t1);
p1.add(b_execute);
p2=new JPanel();
p2.add(l2);
p2.add(jsp);
mp=new JPanel();
Container ct=getContentPane();
ct.add(p1,BorderLayout.NORTH);
ct.add(p2,BorderLayout.CENTER);
setTitle("Demo");
setSize(550,400);
setVisible(true);
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:abc","scott","tiger");
JOptionPane.showMessageDialog(this,"Database Connected");
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in connection"+e);
}
}
public Vector displayData(String query)
{
try{
st=con.createStatement();
rs=st.executeQuery(query);
rsmd=rs.getMetaData();
int cols=rsmd.getColumnCount();
head=new Vector();
for(int i=1;i<=cols;i++)
{
head.add(rsmd.getColumnName(i));
}
data=new Vector();
data.add(head);
while(rs.next())
{
row=new Vector();
for(int i=1;i<=cols;i++)
{
row.add(rs.getString(i));
}
data.add(row);
}
}catch(Exception e)
{
head=new Vector();
head.add("No data found");
data=new Vector();
data.add(head);
}
return data;
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b_execute)
{
try
{
String query=t1.getText();
data=displayData(query);
head=(Vector)data.elementAt(0);
data.removeElementAt(0);
DefaultTableModel dtm=new DefaultTableModel(data,head);
jtab.setModel(dtm);
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in execute "+e);
}
}
}
public static void main(String arg[])
{
new JdbcOracleSelectAll();
}
}
import java.sql.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
public class JdbcOracleSelectJF extends JFrame implements ActionListener
{
Connection con;
ResultSet rs;
Statement st;
PreparedStatement pst;
JLabel l1,l2,l3;
JTextField t1,t2,t3;
JButton b_insert,b_first,b_next,b_pre,b_last,b_clear;
JPanel p,p1,p2,mp;
public JdbcOracleSelectJF()
{
l1=new JLabel("Roll");
l2=new JLabel("Name");
l3=new JLabel("Contactno");
t1=new JTextField(20);
t2=new JTextField(20);
t3=new JTextField(20);
b_insert=new JButton("Insert");
b_insert.addActionListener(this);
b_first=new JButton(" << ");
b_first.addActionListener(this);
b_pre=new JButton(" < ");
b_pre.addActionListener(this);
b_next=new JButton(" > ");
b_next.addActionListener(this);
b_last=new JButton(" >> ");
b_last.addActionListener(this);
b_clear=new JButton(" Clear");
b_clear.addActionListener(this);
p=new JPanel(new GridLayout(3,2));
p.add(l1);
p.add(t1);
p.add(l2);
p.add(t2);
p.add(l3);
p.add(t3);
p1=new JPanel();
p1.add(b_insert);
p1.add(b_clear);
p2=new JPanel();
p2.add(b_first);
p2.add(b_pre);
p2.add(b_next);
p2.add(b_last);
mp=new JPanel(new GridLayout(3,1));
mp.add(p);
mp.add(p1);
mp.add(p2);
Container ct=getContentPane();
ct.setLayout(new FlowLayout());
ct.add(mp);
setTitle("Demo");
setSize(550,400);
setVisible(true);
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:abc","scott","tiger");
JOptionPane.showMessageDialog(this,"Database Connected");
st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs=st.executeQuery("select * from student_xx");
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in connection"+e);
}
}
public void display()
{
try{
t1.setText(""+rs.getInt(1));
t2.setText(""+rs.getString(2));
t3.setText(""+rs.getInt(3));
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in display "+e);
}
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b_clear)
{
t1.setText("");
t2.setText("");
t3.setText("");
t1.requestFocus();
}
if(ae.getSource()==b_insert)
{
try
{
int r=Integer.parseInt(t1.getText());
String nm=t2.getText();
int ct=Integer.parseInt(t3.getText());
pst=con.prepareStatement("insert into student_xx values(?,?,?)");
pst.setInt(1,r);
pst.setString(2,nm);
pst.setInt(3,ct);
pst.executeUpdate();
JOptionPane.showMessageDialog(this,"Record inserted successfully");
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in insert "+e);
}
}
if(ae.getSource()==b_first)
{
try{
rs.first();
display();
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in first "+e);
}
}
if(ae.getSource()==b_pre)
{
try{
if(rs.previous()==false)
{
JOptionPane.showMessageDialog(this,"This is the 1st Record of File ");
}else
display();
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in pre "+e);
}
}
if(ae.getSource()==b_next)
{
try{
if(rs.next()==false)
{
JOptionPane.showMessageDialog(this,"This is the Last Record ");
}else
display();
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in next "+e);
}
}
if(ae.getSource()==b_last)
{
try{
rs.last();
display();
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in last "+e);
}
}
}
public static void main(String arg[])
{
new JdbcOracleSelectJF();
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class JMenuDemo extends JFrame implements ActionListener
{
JMenuBar mb;
JMenu f,e,f1,v,h;
JMenuItem n,o,s,ex,c1,c2,p1,d1,sa;
JTextArea a;
JScrollPane sp;
JFileChooser fc;
FileDialog fd;
JMenuDemo()
{
mb=new JMenuBar();
fc=new JFileChooser();
f=new JMenu("File");
e=new JMenu("Edit");
f1=new JMenu("Format");
v=new JMenu("View");
h=new JMenu("Help");
mb.add(f);
mb.add(e);
mb.add(f1);
mb.add(v);
mb.add(h);
n=new JMenuItem("New",KeyEvent.VK_CONTROL+KeyEvent.VK_N) ;
// n.setMnemonic();
n.addActionListener(this);
o=new JMenuItem("Open") ;
o.addActionListener(this);
s=new JMenuItem("Save") ;
s.addActionListener(this);
ex=new JMenuItem("Exit") ;
ex.addActionListener(this);
c1=new JMenuItem("Cut") ;
c2=new JMenuItem("Copy") ;
p1=new JMenuItem("Past") ;
d1=new JMenuItem("Delete") ;
sa=new JMenuItem("Select All") ;
sa.addActionListener(this);
c1.addActionListener(this);
c2.addActionListener(this);
p1.addActionListener(this);
d1.addActionListener(this);
a=new JTextArea();
sp=new JScrollPane(a,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
Container ct=getContentPane();
ct.add(sp);
f.add(n);
f.add(o);
f.add(s);
f.addSeparator();
f.add(ex);
e.add(c1);
e.add(c2);
e.add(p1);
e.add(sa);
e.addSeparator();
e.add(d1);
setJMenuBar(mb);
setTitle("Demo");
setSize(400,400);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==c1)
{
a.cut();
}
if(ae.getSource()==c2)
{
a.copy();
}
if(ae.getSource()==p1)
{
a.paste();
}
if(ae.getSource()==n)
{
a.setText("");
}
if(ae.getSource()==ex)
{
System.exit(0);
}
if(ae.getSource()==d1)
{
a.replaceRange("", a.getSelectionStart(),a. getSelectionEnd());
}
if(ae.getSource()==o)
{
try{
fc.showOpenDialog(this);
File f=fc.getSelectedFile();
FileReader fr=new FileReader(f);
BufferedReader br=new BufferedReader(fr);
String data="";
a.setText("");
while((data=br.readLine())!=null)
{
a.append(data+"\n");
}
fr.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error is"+e);
}
}
if(ae.getSource()==s)
{
try
{
fc.showSaveDialog(this);
File f = fc.getSelectedFile();
FileWriter fw=new FileWriter(f);
String s="";
s=a.getText();
// String gn=getName(f);
fw.write(s+"\n");
fw.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error is"+e);
}
}
if(ae.getSource()==sa)
{
a.selectAll();
}
}
public static void main(String arg[])
{
new JMenuDemo();
}
}package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.sql.*;
public final class JObportal_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.Vector _jspx_dependants;
private org.apache.jasper.runtime.ResourceInjector _jspx_resourceInjector;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html;charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.apache.jasper.runtime.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write(" out.write(" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
out.write("\n");
out.write("\n");
out.write(" \n");
out.write(" \n");
out.write("
out.write("
\n"); out.write(" \n");
out.write("
out.write("
\n");
out.write("
\n");
out.write("
out.write(" ENTER THE DETAILS
\n"); out.write(" Emp No
\n");
out.write(" Name
\n");
out.write(" Age
\n");
out.write(" Sex Male \n");
out.write(" \n");
out.write(" Female\n");
out.write("
\n");
out.write("\n");
out.write(" Address
\n");
out.write(" Area Nellai \n");
out.write(" Madurai \n");
out.write(" Trichy \n");
out.write(" Chennai
\n");
out.write("\n");
out.write(" Nationality
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write("
\n"); out.write(" Religion:
\n");
out.write(" \n");
out.write("\n");
out.write("
\n"); out.write("\n");
out.write(" ");
try
{
String no=request.getParameter("no");
String name=request.getParameter("name");
String age=request.getParameter("age");
String sex=request.getParameter("gender");
String add=request.getParameter("add");
String area=request.getParameter("chk1,chk2,chk3,chk4");
/*if(request.getParameter("chk1")!=null)
{
String area=request.getParameter("chk1");
}
else if(request.getParameter("chk2")!=null)
{
String area=request.getParameter("chk2");
}
else if(request.getParameter("chk3")!=null)
{
String area=request.getParameter("chk3");
}
else(request.getParameter("chk4")!=null)
{
String area=request.getParameter("chk4");
}*/
String nation=request.getParameter("nation");
String rel=request.getParameter("religion");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection("jdbc:odbc:JOB");
Statement s=c.createStatement();
ResultSet rs=s.executeQuery("select * from job");
while(rs.next())
{
out.println("
out.println("
out.println("
out.println("
out.println("
out.println("
out.println("
out.println("
out.println("
out.println("
out.println("
"); out.println("
"); }
s.executeUpdate("insert into job values ("+no+",'"+name+"',"+age+",'"+sex+"','"+add+"','"+area+"','"+nation+"','"+rel+"') ");
}
catch(SQLException e1)
{
out.println(e1.getMessage());
}
out.write("\n");
out.write("\n");
out.write("
\n"); out.write("
\n"); } catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class JOptionDemo extends JFrame implements ActionListener
{
JButton b1,b2,b3,b4,b5;
JPanel p1,p2,mp;
JOptionDemo()
{
b1=new JButton("ShowPlainDialog");
b1.addActionListener(this);
b2=new JButton("ShowInfoDialog");
b2.addActionListener(this);
b3=new JButton("ShowErrorDialog");
b3.addActionListener(this);
b4=new JButton("ShowQueDialog");
b4.addActionListener(this);
b5=new JButton("ShowWarningDialog");
b5.addActionListener(this);
p1=new JPanel();
p1.add(b1);
p1.add(b2);
p1.add(b3);
p2=new JPanel();
p2.add(b4);
p2.add(b5);
mp=new JPanel(new GridLayout(2,1));
mp.add(p1);
mp.add(p2);
Container ct=getContentPane();
ct.setLayout(new FlowLayout());
ct.add(mp);
setTitle("Demo");
setSize(400,400);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
String title="";
int msgtype=0;
String msg="Hello Friends";
if(ae.getSource()==b1)
{
title="PlainDialog";
msgtype=JOptionPane.PLAIN_MESSAGE;
}
if(ae.getSource()==b2)
{
title="Info";
msgtype=JOptionPane.INFORMATION_MESSAGE;
}
if(ae.getSource()==b3)
{
title="Error";
msgtype=JOptionPane.ERROR_MESSAGE;
}
if(ae.getSource()==b4)
{
title="Que";
msgtype=JOptionPane.QUESTION_MESSAGE;
}
if(ae.getSource()==b5)
{
title="Warning";
msgtype=JOptionPane.WARNING_MESSAGE;
}
JOptionPane.showMessageDialog(this,msg,title,msgtype);
}
public static void main(String arg[])
{
new JOptionDemo();
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class JOptionDemo2 extends JFrame implements ActionListener
{
JButton b1;
JPanel p1;
JOptionDemo2()
{
b1=new JButton("ShowInputDialog");
b1.addActionListener(this);
p1=new JPanel();
p1.add(b1);
Container ct=getContentPane();
ct.setLayout(new FlowLayout());
ct.add(p1);
setTitle("Demo");
setSize(400,400);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
String title="";
int msgtype=0;
String msg="Enter Number";
String msg1="Invalid Input";
try
{
String s=JOptionPane.showInputDialog(msg);
if(s!=null)
{
int x=Integer.parseInt(s);
int n=x*x;
JOptionPane.showMessageDialog(this,"Square of "+x+" is "+n,title,msgtype);
}
else{
JOptionPane.showMessageDialog(this,"Method was Canceled",title,msgtype);
}
}catch(Exception e)
{
title="Error";
msgtype=JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(this,msg1,title,msgtype);
}
}
public static void main(String arg[])
{
new JOptionDemo2();
}
}
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javassist.bytecode.stackmap.BasicBlock.Catch;
import java.sql.*;
public final class Jsp_0020JDBC_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.Vector _jspx_dependants;
private org.apache.jasper.runtime.ResourceInjector _jspx_resourceInjector;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html;charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.apache.jasper.runtime.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write(" out.write(" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
out.write("\n");
out.write("\n");
out.write(" \n");
out.write(" \n");
out.write("
out.write("
\n"); out.write(" \n");
out.write(" ");
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection("jdbc:odbc:student");
Statement s=c.createStatement();
ResultSet rs=s.executeQuery("select * from stud");
while(rs.next())
{
out.println("
out.println("
");
out.println("
out.println("
out.println("
out.println("
"); out.println("
"); }
String rno="82604";
String name="Richard";
String age="25";
s.executeUpdate("insert into stud values("+rno+",'"+name+"',"+age+")");
}
catch(SQLException e)
{
out.println(e.getMessage());
}
out.write("\n");
out.write("
\n"); out.write("
\n"); } catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JTabbedDemo extends JFrame
{
JTabbedPane jtab;
JTabbedDemo()
{
jtab =new JTabbedPane();
jtab.addTab("Sqr",new sqr());
jtab.addTab("Cube",new cub());
getContentPane().add(jtab);
setTitle("Demo");
setSize(600,600);
setVisible(true);
}
public static void main(String arg[])
{
new JTabbedDemo();
}
}
class sqr extends JPanel implements ActionListener
{
JTextField t1,t2;
JLabel l1,l2;
JButton b1;
JPanel p1;
sqr()
{
l1=new JLabel("NUM");
l2=new JLabel("Sqr");
t1=new JTextField(20);
t2=new JTextField(20);
b1=new JButton("SQUARE");
b1.addActionListener(this);
p1=new JPanel(new GridLayout(3,2));
p1.add(l1);
p1.add(t1);
p1.add(l2);
p1.add(t2);
p1.add(b1);
add(p1);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
{
int a=Integer.parseInt(t1.getText());
int x=a*a;
t2.setText(""+x);
}
}
}
class cub extends JPanel implements ActionListener
{
JTextField t1,t2;
JLabel l1,l2;
JButton b1;
JPanel p1;
cub()
{
l1=new JLabel("NUM");
l2=new JLabel("Sqr");
t1=new JTextField();
t2=new JTextField();
b1=new JButton("Cube");
b1.addActionListener(this);
p1=new JPanel(new GridLayout(3,2));
p1.add(l1);
p1.add(t1);
p1.add(l2);
p1.add(t2);
p1.add(b1);
add(p1);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
{
int a=Integer.parseInt(t1.getText());
int x=a*a*a;
t2.setText(""+x);
}
}
}
import java.awt.*;
import javax.swing.*;
public class JTableDemo extends JFrame
{
JTable jtab;
JScrollPane jsp;
JTableDemo()
{
Object cols[]={"Role","Name","Contact No"};
Object rows[][]={{"1","abc","123456"},{"2","xyz","56789"}};
jtab=new JTable(rows,cols);
int vsp=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
int hsp=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
jsp=new JScrollPane(jtab,vsp,hsp);
getContentPane().add(jsp);
setTitle("Demo");
setSize(400,400);
setVisible(true);
}
public static void main(String arg[])
{
new JTableDemo();
}
}
import javax.swing.*;
class jtbl
{
public static void main(String[] args)
{
JFrame f=new JFrame("MyFrame");
String h[]={"Sno","Sname"};
Object data[][]={{"101","Raj"},{"102","Ram"}};
JTable t=new JTable(data,h);
JPanel p=new JPanel();
p.add(t);
f.getContentPane().add(p);
f.setSize(300,400);
f.show();
}
}
import java.io.*;
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
*/
public class kapp extends Applet implements ActionListener
{
Button b1;
TextField t1,t2;
public void init()
{
setLayout(null);
b1 = new Button("new");
t2= new TextField(20);
t1= new TextField(20);
add(t2);
add(t1);
add(b1);
t2.setBounds(100,100,50,50);
t1.setBounds(100,200,50,50);
b1.setBounds(100,300,50,50);
t1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String str;/* = e.getActionCommand();
if(str.equals("new"))
{*/
int a = Integer.parseInt(t2.getText());
a = a*a;
str = a + "";
t1.setText(str);
//}
}
}import java.util.Scanner;
import java.io.*;
public class key
{
public static void main(String args[]) throws IOException
{
Scanner s=new Scanner(System.in);
System.out.println(s.next());
String name = s.next();
System.out.println(name);
DataInputStream in = new DataInputStream(System.in);
name=in.readLine();
System.out.println(name);
}}import java.util.Scanner;
import java.io.*;
public class key1
{
public static void main(String args[]) throws IOException
{
Scanner s=new Scanner(System.in);
System.out.println(s.next());
String name = s.next();
System.out.println(name);
DataInputStream in = new DataInputStream(System.in);
name=in.readLine();
System.out.println(name);
InputStreamReader il= new InputStreamReader (System.in);
BufferedReader br = new BufferedReader(il);
name=br.readLine();
System.out.println(name);
}}import java.util.*;
import java.io.*;
/**
* Title: K-Means Clustering
* Description: Clustering using the K-Means approach
* Copyright: Copyright (c) 2003
* @author Huiyong Xiao
* @version 1.0
*/
public class KMeans {
private File namefile = null;
private File datafile = null;
private int k = -1; // k in 'KMeans'
private ArrayList seedIDlist = new ArrayList(); // to store the IDs (NOs) of the tuples.
private ArrayList centroidlist = new ArrayList(); // to store the centroids of the clusters.
private ArrayList clusterlist = new ArrayList(); // to store the clusters. Each cluster is a list of IDs of the tuples
private ArrayList attrlist = new ArrayList(); // to store the attributes
private ArrayList valuelist = new ArrayList(); // to store all the tuples (cases). Each tuple is a list of attrvalues.
private ArrayList classlist=new ArrayList();
public KMeans() {
}
public static void main(String[] args) throws Exception {
try {
// load the file specified by filename.
System.out.print("Please input the file name: ");
BufferedReader lineReader = new BufferedReader(new InputStreamReader(
System.in));
String fileitemname = lineReader.readLine();
KMeans km = new KMeans();
if (km.loadFiles(fileitemname) == false) {
return;
}
// handle the inputted 'K'.
while (true) {
System.out.print("Please input 'K' (int): ");
try {
int k = Integer.parseInt(lineReader.readLine());
km.setK(k);
break;
}
catch (NumberFormatException ee) {
System.out.println("Format error! Please input an integer!!!");
}
}
km.seedIDlist.clear();
// handle the method of choosing seeds.
while (true) {
System.out.print("Pick up seeds Randomly or Specifically? (R/S): ");
String st = lineReader.readLine();
if (st.equals("R")) {
km.seedingRandomly();
break;
}
else if (st.equals("S")) {
km.seedingSpecifically();
break;
}
else {
System.out.println("Input error! Please input 'R' or 'S'!!!");
}
}
km.clustering();
String outputFilename = "";
do {
System.out.print("Please specify the output file itemname: ");
outputFilename = lineReader.readLine();
}
while (!km.output(outputFilename));
}
catch (Exception e) {
}
}
/**
* Validate file names and Load data from files.
* @param fileitemname specifies the file name not including the extension.
* @return TRUE: The files exist in the current directory;
* FALSE: Any of the files doesn't exist in the current directory.
*/
public boolean loadFiles(String fileitemname) {
// validate if the files exist.
this.namefile = new File("./" + fileitemname + ".names");
if (!this.namefile.exists()) {
System.out.println("The file .names doesn't exist!");
return false;
}
this.datafile = new File("./" + fileitemname + ".data");
if (!this.datafile.exists()) {
System.out.println("The file .data doesn't exist!");
return false;
}
this.loadName();
this.loadData();
return true;
}
/**
* Load attr from the '.names' file.
*/
protected boolean loadName() {
try {
BufferedReader reader = new BufferedReader(new FileReader(this.namefile));
String line = "";
int ind = 0;
while ( (line = reader.readLine()) != null) {
// remove the annotation
ind = line.indexOf('|');
if (ind >= 0) {
line = line.trim().substring(0, ind).trim();
}
if (line.equals("")) {
continue;
}
ind = line.indexOf(':');
if (ind >= 0) {
// read attribute names into the "attrlist".
String name = line.substring(0, ind);
this.attrlist.add(name);
}
} // while readLine()
return true;
}
catch (IOException ex) {
System.out.println("File I/O error. Please verify the .names file");
ex.printStackTrace();
return false;
}
}
/**
* Load data from the '.data' file.
*/
protected void loadData() {
try {
BufferedReader reader = new BufferedReader(new FileReader(this.datafile));
String line = "";
int ind = 0;
while ( (line = reader.readLine()) != null) {
// remove the annotation
ind = line.indexOf('|');
if (ind >= 0) {
line = line.trim().substring(0, ind).trim();
}
if (line.equals("")) {
continue;
}
ArrayList tuple = new ArrayList();
ind = line.indexOf(',');
while (ind > 0) {
String attrvalue = line.substring(0, ind);
tuple.add(new Double(attrvalue));
line = line.substring(ind + 1).trim();
ind = line.indexOf(',');
} // while
//tuple.add(line);
//this.classlist.add(line);
this.valuelist.add(tuple);
} // while readLine()
}
catch (IOException ex) {
System.out.println("File I/O error. Please verify the .data file");
ex.printStackTrace();
}
}
/**
* Set the value of 'K'.
*/
public void setK(int k) {
this.k = k;
}
/**
* Generate the k seeds randomly.
*/
public void seedingRandomly() {
int upper = this.valuelist.size();
Random rg = new Random();
for (int i = 0; i < k; i++) {
this.seedIDlist.add(new Integer(rg.nextInt(upper))); // nextInt returns an integer between [0, uppper-1]
}
}
/**
* Generate the k seeds manually.
*/
public void seedingSpecifically() {
try {
BufferedReader lineReader = new BufferedReader(new InputStreamReader(
System.in));
int upper = this.valuelist.size();
int i = 1;
while (i <= this.k) {
System.out.print("Please input No " + i + " seed (int[0.." + (upper - 1) +
"]): ");
try {
int seedID = Integer.parseInt(lineReader.readLine());
if (seedID < 0 || seedID > (upper - 1)) {
System.out.println(
"Format error! Please input an integer between [0.." +
(upper - 1) +
"]!!!");
continue;
}
this.seedIDlist.add(new Integer(seedID));
i++;
}
catch (NumberFormatException ee) {
System.out.println(
"Format error! Please input an integer between [0.." + (upper - 1) +
"]!!!");
}
} // while
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* Cluster the whole dataset.
* Inputs: 1. the tuples in the "valuelist".
* 2. the seeds in the "seedIDlist". Also as the Centroids.
* Output: 1. the clusters in the "clusterlist".
*/
public void clustering() {
// initialize the centroid list using the seedIDlist.
System.out.println(" clustering");
for (int j = 0; j < this.k; j++) {
int id = ( (Integer)this.seedIDlist.get(j)).intValue();
this.centroidlist.add( (ArrayList)this.valuelist.get(id));
}
double oldError = 0;
double newError = 0;
double oldErrorDec = 0;
double newErrorDec = 0;
int loopNo = 0;
do {
// initialize the clusters in the cluster list
this.clusterlist.clear();
for (int i = 0; i < this.k; i++) {
this.clusterlist.add(new ArrayList());
}
// clustering...
for (int i = 0; i < this.valuelist.size(); i++) {
ArrayList tuple = (ArrayList)this.valuelist.get(i);
double minDistance = 0;
int nearestCenterID = 0;
// find the nearest centroid for the current tuple.
for (int j = 0; j < this.k; j++) {
ArrayList centroid = (ArrayList)this.centroidlist.get(j);
// computer the Euclidean distance between the tuple and the centroid.
double distance = euDistance(tuple, centroid);
if (j == 0 || distance < minDistance) {
minDistance = distance;
nearestCenterID = j;
}
} // for j
// add the Index (i) of the current tuple into the corresponding Cluster (nearestCenterID).
ArrayList cluster = (ArrayList)this.clusterlist.get(nearestCenterID);
cluster.add(new Integer(i));
this.clusterlist.set(nearestCenterID, cluster);
} // for i
// recompute the centroids and update them in the 'centroidlist'.
for (int j = 0; j < this.k; j++) {
ArrayList newCentroid = this.mean( (ArrayList)this.clusterlist.get(j));
this.centroidlist.set(j, newCentroid);
}
System.out.println(" clustering end");
// check the loop-ending condition - squaredError.
loopNo++;
newError = this.squaredError();
oldError = newError;
if (loopNo != 1) {
newErrorDec = oldError - newError;
}
if (loopNo <= 2) {
oldErrorDec = newErrorDec;
}
else if (oldErrorDec >= newErrorDec) {
break;
}
}
while (true);
}
/**
* Compute the Euclidean Distance between two tuples.
*/
protected double euDistance(ArrayList tuple1, ArrayList tuple2) {
double sum = 0;
for (int i = 0; i < tuple1.size(); i++) {
double value1 = ( (Double) tuple1.get(i)).doubleValue();
double value2 = ( (Double) tuple2.get(i)).doubleValue();
sum += Math.pow( (value1 - value2), 2);
}
return Math.sqrt(sum);
}
/**
* Compute the Squared Error.
*/
protected double squaredError() {
double error = 0;
for (int i = 0; i < this.k; i++) {
ArrayList cluster = (ArrayList)this.clusterlist.get(i);
ArrayList centroid = (ArrayList)this.centroidlist.get(i); // the centroid is the mean of the cluster.
double sum = 0;
for (int j = 0; j < cluster.size(); j++) {
ArrayList tuple = (ArrayList)this.valuelist.get( ( (Integer) cluster.
get(i)).intValue());
double distance = this.euDistance(centroid, tuple);
sum += (distance * distance);
}
error += sum;
}
return error;
}
/**
* Compute the mean of all the tuples in the each cluster.
*/
protected ArrayList mean(ArrayList cluster) {
ArrayList meanTuple = new ArrayList();
// initialize each attrvalue to '0';
for (int i = 0; i < this.attrlist.size(); i++) {
meanTuple.add(new Double(0));
}
// accumulate.
for (int i = 0; i < cluster.size(); i++) {
ArrayList tuple = (ArrayList)this.valuelist.get( ( (Integer) cluster.get(
i)).intValue());
// accumulate each attrvalue.
for (int j = 0; j < this.attrlist.size(); j++) {
double sum = ( (Double) meanTuple.get(j)).doubleValue();
double adder = ( (Double) tuple.get(j)).doubleValue();
meanTuple.set(j, new Double(sum + adder));
}
}
// compute the mean
for (int i = 0; i < this.attrlist.size(); i++) {
double sum = ( (Double) meanTuple.get(i)).doubleValue();
meanTuple.set(i, new Double(sum / cluster.size()));
}
return meanTuple;
}
/**
* Output the clustering results.
*/
public boolean output(String filename) {
try {
// check if any of the possible output files exists.
boolean fileExist = false;
for (int i = 0; i < this.centroidlist.size(); i++) {
File outputFile = new File("./" + filename + "_" + (i + 1) + ".rsl");
if (outputFile.exists()) {
fileExist = true;
break;
}
}
if (fileExist) {
BufferedReader lineReader = new BufferedReader(new InputStreamReader(
System.in));
while (true) {
System.out.print("The filename has existed. Overwrite? (Y/N)");
String st = lineReader.readLine();
if (st.equals("Y")) {
break;
}
else if (st.equals("N")) {
return false;
}
}
} // if
// Output: 1. Print the centriod and the number of data points in each cluster.
// 2. Store the actual data points of each cluster in a separate file.
for (int i = 0; i < this.centroidlist.size(); i++) {
ArrayList centroid = (ArrayList)this.centroidlist.get(i);
ArrayList cluster = (ArrayList)this.clusterlist.get(i);
// 1. Print the centriod and the number of data points in each cluster.
int size = cluster.size();
System.out.println("-------- Cluster " + (i + 1) + " (" + size +
" data) --------");
System.out.print(" Centroid: (");
for (int j = 0; j < this.attrlist.size(); j++) {
double value = ( (Double) centroid.get(j)).doubleValue();
if (j == this.attrlist.size() - 1) {
System.out.println(this.double2string(value, 2) + ")\n"); // last attribute.
}
else {
System.out.print(this.double2string(value, 2) + ", ");
}
}
// 2. Store the actual data points of each cluster in a separate file.
File outputFile = new File("./" + filename + "_" + (i + 1) + ".rsl");
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile, false));
StringBuffer buf = new StringBuffer();
for (int m = 0; m < cluster.size(); m++) {
ArrayList tuple = (ArrayList)this.valuelist.get( ( (Integer) cluster.
get(m)).intValue());
for (int j = 0; j < this.attrlist.size(); j++) {
double value = ( (Double) tuple.get(j)).doubleValue();
if (j == this.attrlist.size()-1 ) {
buf.append(this.double2string(value, 2) +"\n"); // last attribute.
}
else {
buf.append(this.double2string(value, 2) + ", "); // last attribute.
}
}
}
writer.write(buf.toString());
writer.close();
} // for
}
catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
private String double2string(double d, int decimal) {
String str = Double.toString(d);
int length = str.indexOf('.') + decimal + 1;
if (str.length() < length) {
length = str.length();
}
return str.substring(0, length);
}
}import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
*/
public class la extends Applet
{
public void init()
{
Label one = new Label("one");
Label two = new Label("two");
Label three = new Label("three");
add(one);
add(two);
add(three);
}
} // To create a label //
/* public java.awt.Label();
public java.awt.Label(java.lang.String);
public java.awt.Label(java.lang.String,int); */
import java.applet.Applet;
import java.awt.*;
//
public class label extends Applet {
public void init() {
Label l1,l2,l3 ;
Label l4,l5 ;
l1=new Label(" M ");
l2=new Label(" C ");
l3=new Label(" A ");
l4=new Label(" center",Label.CENTER);
l5=new Label(" right ",Label.RIGHT);
add(l4); add(l5); add(l1); add(l2); add(l3);
}
}
import java.awt.*;
public class Labeltextdemo extends Frame
{
Label l1,l2;
TextField t1,t2; // declaration
public Labeltextdemo()
{
l1=new Label("Num");
l2=new Label("Square"); // construction
t1=new TextField(20);
t2=new TextField(20);
setLayout(null);
l1.setBounds(20,30,60,20);
l2.setBounds(20,70,60,20);
t1.setBounds(100,30,60,20);
t2.setBounds(100,70,60,20);
add(l1);
add(t1); // adding component
add(l2);
add(t2);
setTitle("Text Label demo");
setSize(600,600);
setVisible(true);
}
public static void main(String args[])
{
new Labeltextdemo();
}
}import java.awt.*;
public class Bound extends Frame
{
Label l1,l2;
TextField t1,t2; // declaration
public Bound()
{
l1=new Label("Num");
l2=new Label("Square"); // construction
t1=new TextField(20);
t2=new TextField(20);
setLayout(null);
l1.setBounds(20,30,60,20);
l2.setBounds(20,70,60,20);
t1.setBounds(100,30,60,20);
t2.setBounds(100,70,60,20);
add(l1);
add(t1); // adding component
add(l2);
add(t2);
setTitle("Text Label demo");
setSize(600,600);
setVisible(true);
}
public static void main(String args[])
{
new Bound();
}
}import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* */
public class Labeltextdemoapp extends Applet
{
Label l1,l2;
TextField t1,t2; // declaration
public void init()
{
l1=new Label("Num");
l2=new Label("Square"); // construction
t1=new TextField(20);
t2=new TextField(20);
setLayout(new FlowLayout());
add(l1);
add(t1); // adding component
add(l2);
add(t2);
}
} //to create list box
import java.applet.Applet;
import java.awt.*;
//
public class list extends Applet {
public void init() {
List seca=new List();
List secb=new List();
seca.addItem("mani"); seca.addItem("chandru");
seca.addItem("senthil"); seca.addItem("mohan");
seca.addItem("anand"); seca.addItem("amani");
seca.addItem("achandru"); seca.addItem("asenthil");
seca.addItem("amohan"); seca.addItem("aanand");
secb.addItem("subash"); secb.addItem("bala");
secb.addItem("sankar"); secb.addItem("raja");
add(seca); //to add the choice in default layout
add(secb);
}
}
class Loading
{
int x=2,y=4,z;
void add()
{
z=x+y;
System.out.println("The value of Z1:"+z);
}
void add(int x1)
{
x=x1;
z=x+y;
System.out.println("The value of Z2:"+z);
}
void add(int x1,int y1)
{
x=x1;
y=y1;
z=x+y;
System.out.println("The value of Z3:"+z);
}
public static void main(String arg[])
{
Loading t1=new Loading();
t1.add();
t1.add(10);
t1.add(10,20);
}
}
No comments:
Post a Comment