Sunday, June 19, 2016

Sample Java Programs

/*

*/



import java.applet.Applet;
import java.awt.Graphics;


public class app extends Applet{

public void start(){
System.out.println("applet started");
}

public void run(){

System.out.println("applet run");
}

public void stop()
{
System.out.println("applet stopped");
}

public void destroy(){
System.out.println("applet destroyed");
}

public void paint(Graphics g){

g.drawString ("bala welcome ",20,20);
}


}import java.io.*;
import java.awt.*;
import java.applet.Applet.*;
import java.applet.*;
public class app10 extends Applet{
Button A = new Button("color");

public void init(){

add(A);
}
public void paint(Graphics g){

showStatus ("applet");
}

public boolean action(Event op,Object gp){
if (op.target instanceof Button)
if(gp.equals("color")){
setBackground(Color.red);
A.setLabel("RED");

return true;}
return false;}
}/* Applet Threads*/
/*
Definition: Draw dots at a random location in its display area every 200  milliseconds
  any dots that already exist are not erased.
The method update() has been overridden. Therefore, the applet display
area is not cleared with the background color before the paint() method
is invoked. This causes the dos to accumulate as the applet executes.
*/
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.*;
import java.awt.Font;
/*


*/
public class Applet10 extends Applet implements Runnable
{
 Thread t;
 public void init()
 {
  // Started new Thread
  t = new Thread(this);
  t.start();
 }
 public void run()
 {
  try
  {
   while(true)
   {
    // Request a repaint
    repaint();
    Thread.sleep(200);
   }
  }
  catch(Exception e)
  {
  }
 }
 public void update(Graphics g)
 {
  paint(g);
 }
 public void paint(Graphics g)
 {

  Dimension d = getSize();
  int x = (int)(Math.random() * d.width);
  int y = (int)(Math.random() * d.height);
  g.fillRect(x,y,5,5);
 }
}/*

*/
import java.awt.*;
import java.applet.Applet;

public class aptest extends Applet {
/*
public void init(){
}*/

public void paint(Graphics g)
{
g.drawString("balaji",20,20);
}


}import java.util.Scanner;
import java.io.*;


class ArrayOrder
{

public static void main(String args[])

{

int n;


Scanner in= new Scanner (System.in);

System.out.println("array limit: ");

n= in.nextInt();

int array[] = new int[n];


//System.out.println(n);


System.out.println("enter the elements present int the array");


for (int i=0;i{
System.out.println("element "+( i+1));
array[i] = in.nextInt();
}

int temp;

for (int i=0;i{
for (int j=i+1;j{
if(array[i]>array[j])
{

temp=array[i];
array[i]=array[j];
array[j]=temp;


}



}
}

for (int i=0;i{
System.out.println(" sorted elements:  " + array[i]);

}



}


}//[PM 10:34:43] slvganesh: /*
 //* (#) Attendance.java  July 25, 2011
 //*/

public class Attendance {

  public static void main(String[] args) {

    String students[] = new String[10];
    int days[] = new int[10];
    int status[][] = new int[10][10]; // row, col

    java.util.Scanner scan = new java.util.Scanner(System.in);

    System.out.print("\n Enter no.of students: ");
    int n = scan.nextInt();
   
    for (int i = 0; i < n; i++) {
      System.out.print(" Enter Student Name: ");
      students[i] = scan.nextLine();
    }

    for (int i = 0; i < 10; i++) {
      System.out.print("\n Enter the date: ");
      days[i] = scan.nextInt();

      System.out.println("\nEnter the attendance..");
      for (int j = 0; j < n; j++) {
        System.out.print(students[j] + ": ");
        status[i][j] = scan.nextInt();
      }
    }  
  }
}Compiled from "BufferedReader.java"
public class java.io.BufferedReader extends java.io.Reader{
    public java.io.BufferedReader(java.io.Reader, int);
    public java.io.BufferedReader(java.io.Reader);
    public int read()       throws java.io.IOException;
    public int read(char[], int, int)       throws java.io.IOException;
    java.lang.String readLine(boolean)       throws java.io.IOException;
    public java.lang.String readLine()       throws java.io.IOException;
    public long skip(long)       throws java.io.IOException;
    public boolean ready()       throws java.io.IOException;
    public boolean markSupported();
    public void mark(int)       throws java.io.IOException;
    public void reset()       throws java.io.IOException;
    public void close()       throws java.io.IOException;
    static {};
}

interface tvstation{

String satellitename="satsun";
String cabletvname="suntv";
double signalfrequency=12.3;
public void show();

}


class programme{

String progname;
String sponser;

programme()
{
progname="debugging";
sponser ="infosys";
}




public void display()
{
System.out.println("\n\nprogram display method");
System.out.println(progname);
System.out.println(sponser);
}



}

class Broadcast1 extends programme implements tvstation {

String broadcasttime;
String date;

Broadcast1()
{
broadcasttime="08-30AM";
date="12-nov-2011";

}


public void display()
{
System.out.println("\n\nbroadcast display method");
System.out.println(broadcasttime);
System.out.println(date);
}


public void show()
{
System.out.println("\n\nshow method");
System.out.println(broadcasttime);
System.out.println(date);
System.out.println(satellitename);
System.out.println(cabletvname);
System.out.println(signalfrequency);
System.out.println(progname);
System.out.println(sponser);

}


public static void main(String args[])
{

System.out.println("tvstation program");

Broadcast1 b = new Broadcast1();

b.display();
b.show();
}



}






/**
  This is a simple calculator program can any one take and use.

  */
import javax.swing.*;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
//
public class Calculator extends JApplet {
   public void init() {
      CalculatorPanel calc=new CalculatorPanel();
      getContentPane().add(calc);
      }
   }

   class CalculatorPanel extends JPanel implements ActionListener {
      JButton
n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,plus,minus,mul,div,dot,equal;
      static JTextField result=new JTextField("0",45);
      static String lastCommand=null;
      JOptionPane p=new JOptionPane();
      double preRes=0,secVal=0,res;

      private static void assign(String no)
        {
         if((result.getText()).equals("0"))
            result.setText(no);
          else if(lastCommand=="=")
           {
            result.setText(no);
            lastCommand=null;
           }
          else
            result.setText(result.getText()+no);
         }

      public CalculatorPanel() {
         setLayout(new BorderLayout());
         result.setEditable(false);
         result.setSize(300,200);
         add(result,BorderLayout.NORTH);
         JPanel panel=new JPanel();
         panel.setLayout(new GridLayout(4,4));

         n7=new JButton("7");
         panel.add(n7);
         n7.addActionListener(this);
         n8=new JButton("8");
         panel.add(n8);
         n8.addActionListener(this);
         n9=new JButton("9");
         panel.add(n9);
         n9.addActionListener(this);
         div=new JButton("/");
         panel.add(div);
         div.addActionListener(this);

         n4=new JButton("4");
         panel.add(n4);
         n4.addActionListener(this);
         n5=new JButton("5");
         panel.add(n5);
         n5.addActionListener(this);
         n6=new JButton("6");
         panel.add(n6);
         n6.addActionListener(this);
         mul=new JButton("*");
         panel.add(mul);
         mul.addActionListener(this);

         n1=new JButton("1");
         panel.add(n1);
         n1.addActionListener(this);
         n2=new JButton("2");
         panel.add(n2);
         n2.addActionListener(this);
         n3=new JButton("3");
         panel.add(n3);
         n3.addActionListener(this);
         minus=new JButton("-");
         panel.add(minus);
         minus.addActionListener(this);

         dot=new JButton(".");
         panel.add(dot);
         dot.addActionListener(this);
         n0=new JButton("0");
         panel.add(n0);
         n0.addActionListener(this);
         equal=new JButton("=");
         panel.add(equal);
         equal.addActionListener(this);
         plus=new JButton("+");
         panel.add(plus);
         plus.addActionListener(this);
         add(panel,BorderLayout.CENTER);
      }
      public void actionPerformed(ActionEvent ae)
         {
      if(ae.getSource()==n1) assign("1");
      else if(ae.getSource()==n2) assign("2");
      else if(ae.getSource()==n3) assign("3");
      else if(ae.getSource()==n4) assign("4");
      else if(ae.getSource()==n5) assign("5");
      else if(ae.getSource()==n6) assign("6");
      else if(ae.getSource()==n7) assign("7");
      else if(ae.getSource()==n8) assign("8");
      else if(ae.getSource()==n9) assign("9");
      else if(ae.getSource()==n0) assign("0");
      else if(ae.getSource()==dot)
            {
             if(((result.getText()).indexOf("."))==-1)
                result.setText(result.getText()+".");
           }
      else if(ae.getSource()==minus)
             {
             preRes=Double.parseDouble(result.getText());
             lastCommand="-";
             result.setText("0");
             }
      else if(ae.getSource()==div)
             {
             preRes=Double.parseDouble(result.getText());
             lastCommand="/";
             result.setText("0");
             }
      else if(ae.getSource()==equal)
             {
             secVal=Double.parseDouble(result.getText());
             if(lastCommand.equals("/"))
                  res=preRes/secVal;
             else if(lastCommand.equals("*"))
                  res=preRes*secVal;
             else if(lastCommand.equals("-"))
                  res=preRes-secVal;
             else if(lastCommand.equals("+"))
                  res=preRes+secVal;
             result.setText(" "+res);
             lastCommand="=";
             }
      else if(ae.getSource()==mul)
             {
              preRes=Double.parseDouble(result.getText());
              lastCommand="*";
              result.setText("0");
              }
      else if(ae.getSource()==plus)
              {
              preRes=Double.parseDouble(result.getText());
              lastCommand="+";
              result.setText("0");
              }

       }
 }import java.util.Arrays;


/*
 Convert String to Character Array Example
 This example shows how to convert a given String object to an array
 of character
 */

public class chararr {

  public static void main(String args[]){
    //declare the original String object
    String strOrig = "Hello World";
    //declare the char array
    char[] stringArray,sa2,sa3;

    //convert string into array using toCharArray() method of string class
    stringArray = strOrig.toCharArray();
 sa2= strOrig.toCharArray();
sa3 = strOrig.toCharArray();
    //display the array
    for(int index=0; index < stringArray.length; index++)
      System.out.print(stringArray[index]);

String s="";


   for(int index=0; index < stringArray.length; index++)
s=s+stringArray[index];

//s=arrayToString(stringArray);
System.out.println(s);

if (sa3==sa2){

System.out.println("yes correct!!");
}
else{
System.out.println("incorrect!!");
if (sa3.equals(sa2)){
System.out.println("yes");
}
else{

System.out.println("no");
}

}


for(int index=0; index < stringArray.length; index++)
      System.out.print(sa2[index]);


System.out.println(Arrays.equals(sa2,sa3));

  }

}

/*
Output of the program would be :
Hello World
*//*

*/
import java.awt.Graphics;
 import java.awt.Font;
  import java.util.Date;

  public class DigitalClock extends java.applet.Applet
    implements Runnable {
 
    Font theFont = new Font("TimesRoman",Font.BOLD,24);
   Date theDate;
   Thread runner;

   public void start() {
     if (runner == null) {
       runner = new Thread(this);
       runner.start();
     }
   }

   public void stop() {
     if (runner != null) {
       runner.stop();
       runner = null;
     }
   }
 
   public void run() {
     while (true) {
       theDate = new Date();
       repaint();
      try { Thread.sleep(1000); }
       catch (InterruptedException e) { }
     }
   }

  public void paint(Graphics g) {
     g.setFont(theFont);
     g.drawString(theDate.toString(),10,50);
   }
}
/*

*/
import java.awt.Graphics;
import java.applet.Applet;
import java.awt.Container;
import java.awt.*;

public class dots extends Applet implements Runnable{

Thread t;
public void init(){
t = new Thread(this);
t.start();


}

public void run(){
try{
while(true){

repaint();
 Thread.sleep(1000);
}

}

catch(Exception e){
}
}

public void update(Graphics g){
paint (g);

}


public void paint(Graphics g ){

Dimension d= getSize();
int x= (int) Math.random()*d.width;
int y= (int) Math.random()* d.height;
g.fillRect(x,y,5,5);
}

}


import java.util.*;
//import java.lang.ArrayIndexOutOfBoundsException;
import java.lang.*;

public class exception1{
public static void main(String args[]){
try{
System.out.println("exception program1");




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


Scanner in = new Scanner(System.in);

String sname= in.next();

int array[]= {1,2,3};

//System.out.println(array[5]);

int a=10,b=0;
int c;
if (b==0){
throw new ArithmeticException (" b value not be zero ");
}
//c=a/b;





}


/*catch(Exception e){
System.out.println("error is..." + e);

}*/

catch(ArithmeticException e ){
System.out.println("error is..." + e);
}

catch (ArrayIndexOutOfBoundsException e){

System.out.println("error is..." + e);
}

try{
int array1[]= new int[10];
System.out.println("any Integer");
Scanner in = new Scanner(System.in);

array1[1]= in.nextInt();
}
catch(InputMismatchException e){
System.out.println("error is..." + e);

}





}

}
class exceptiona extends Exception{

exceptiona(String s){
super(s);
}

}

class exceptionb extends exceptiona{

exceptionb(String s){
super(s);

}

}

class exceptionc extends exceptionb{

exceptionc(String s){
super(s);

}


}




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

System.out.println("\n\nexception program\n\n\n");
try{
throw new exceptionb ("sub class'b' exception throwned");

}
catch(exceptiona e){

System.out.println("super class exception'a' is catched.."+e);
e.printStackTrace();
}




}

}class exceptiona extends Exception{
exceptiona(String s){

super(s);
}

}

class exceptionb extends exceptiona
{
exceptionb(String s){

super(s);
}

}

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

System.out.println("\n\n\nexception three program\n\n\n");
try{
throw new exceptiona("throw exception a");
}

catch(exceptionb e)
{

System.out.println(e);
}




}



}class MException extends Exception{
/*public MException(String str)
{
super(str);
}*/
}

public class exception4{


public static void method()throws MException{

try{
exception4.method2();
throw new MException("method throw");
}
catch(MException e)
{
System.out.println("method Exception caught"+ e);
throw e;
}


}

public static void method2() throws MException {

try{
throw new MException("method2 throw");
}
catch(MException e)
{
System.out.println("method2 Exception caught"+ e);

//e.printStackTrace();
throw e;

}

}

public static void main(String args[]){

System.out.println("exception program");

try{

exception4.method();

}
catch(MException e)
{
System.out.println("main Exception caught"+ e);
}

finally{
}

}


}public class exception5{

public static void method()throws Exception{

try{

throw new Exception("method throw error");

}
finally{


}


}




public static void main(String args[]){

System.out.println("\n\n\nexception5 program \n\n\n");

try{

exception5.method();
}
catch(Exception e){

System.out.println("outer scope catch");

System.out.println("error is.." +e);
}


}

}

/*
 * (#) ExceptionDemo.java  Aug 05, 2011
 *
 * Demonstration of basic exceptions.
 */

public class ExceptionDemo {


  public static void main(String[] args) {

    int a = 4, b = 0, c;

    try {
      if (b == 0) {
         throw new DivideByZeroException();
      } else {
         c = a / b;
      }    
    }
    catch(DivideByZeroException e) {
      System.err.println("Exception: " + e);
    }
  }
}

class DivideByZeroException extends Throwable {

  public String toString() {
    return "DivideByZeroException";
  }
}import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class ExitListener extends WindowAdapter {
  public void windowClosing(WindowEvent event) {
System.exit(0);
  }
}
class fact extends Thread{


public void run(){
try{
System.out.println("in thread process");
Thread t;
int n=1;

while (n!=21)
{
int temp=n;
long f=1;
for (int i=1;i{
f=f*i;

//System.out.println(n);

}

System.out.println(f);
Thread.sleep(1000);
n++;
}

}
catch(InterruptedException e){

System.out.println("error is : " + e);


}



}





}



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

System.out.println("factorial program");

fact f= new fact();

f.start();





}


}/*

*/
public class fapplet extends java.applet.Applet{

public void init()
{
System.out.println("init");
}
public void paint(java.awt.Graphics g){
System.out.println("paint");

g.drawString("hello balaji",20,20);
}

public void start()
{
System.out.println("start");
}


public void stop()
{
System.out.println("stop");
}

public void destroy(){

System.out.println("destroy");
}


}


/*
*/

public class hello extends java.applet.Applet {

  public void paint(java.awt.Graphics g) {
    g.drawString("Hello World", 20, 20);
  }
} class Hello1 {
  public String toString() {
   return "Hello..";
 }

 public static void main(String[] args) {
  Hello1 h = new Hello1();

System.out.println(h);
}
}balaji hi hru

/*
 * (#) HelloWorld.java  Aug 05, 2011
 *
 * My first Applet.
 */

import java.applet.*;
import java.awt.*;

/*
*/

public class HelloWorld extends java.applet.Applet {

  public void init() {
    System.out.println("Initializing applet..");
  }

  public void start() {
    System.out.println("Starting Applet..");
  }

  public void paint(java.awt.Graphics g) {
    g.drawString("Hello World", 20, 20);
  }

  public void stop() {
    System.out.println("Applet stopped..");
  }

  public void destroy() {
    System.out.println("Applet terminated..");
  }
}interface point2d{

double x;
double y;

constructor();



}

interface shape2d{

public double getarea();


}


public class square implements shape2d{





}


import java.util.*;
public class Menu {
public static void main (String[] args){
Random generator = new Random();
Scanner sc = new Scanner(System.in);
String Email, Username, Password, pass1, user1;

Username="hello";
Password="hello";

String Name, Surname, Ans;
int age, sqchoice, choice;

System.out.println("Welcome!");
System.out.println("\n[1] Register");
System.out.println("[2] Log in");
System.out.println("[3] Forgot Password/Username");
System.out.println("[4] Quit");
System.out.print("\nEnter your choice: ");
choice = sc.nextInt();
switch(choice){
case 1:
System.out.println("\nKindly enter information below:");
System.out.print("\nName: ");
Name = sc.next();
System.out.print("Surname: ");
Surname = sc.next();
System.out.print("Age: ");
age = sc.nextInt();
System.out.print("Email Address: ");
String input = sc.next();
Email = input;
//.toCharArray();
System.out.print("Username: ");
String input1 = sc.next();
Username = input1;
//.toCharArray();
System.out.print("Password: ");
String input2 = sc.next();
Password = input2;
//.toCharArray();
System.out.println("\nSecurity Questions: ");
System.out.println("[1] What was your childhood nickname?");
System.out.println("[2] What is the name of your favorite childhood friend?");
System.out.println("[3] What is your maternal grandmother's maiden name?");
System.out.println("[4] What is your oldest cousin's first and last name?");
System.out.print("\nEnter your choice: ");
sqchoice = sc.nextInt();
System.out.print("\nAnswer: ");
Ans = sc.next();
int number = generator.nextInt(1000000) + 1;
System.out.println("\nYour Unique Number: "+number);
case 2:
System.out.print("\nUsername: ");
String input3 = sc.next();
user1 = input3;
//.toCharArray();
System.out.print("Password: ");
String input4 = sc.next();
pass1 = input4;
//.toCharArray();
if ((Username.equals(user1)) && (Password.equals(pass1))){
System.out.print("WIN");
}else{
System.out.print("FAIL");
}

break;


}
}
}import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class Notepad extends JFrame implements ActionListener
{
JTextArea t;
JMenuBar mb;
JMenu mf,me,ce;
JMenuItem in,io,is,isa,ie,iu,ip,ic,icu,isal,cd;
JFileChooser jfc;
JColorChooser jcc;
JScrollPane jsp;

public Notepad()
{

  mb=new JMenuBar();
setJMenuBar(mb);
mf=new JMenu("File");
me=new JMenu("Edit");
ce=new JMenu("Color");
mb.add(mf);
mb.add(me);
mb.add(ce);
in=new JMenuItem("New");
io=new JMenuItem("Open");
is=new JMenuItem("Save");
isa=new JMenuItem("SaveAs");
ie=new JMenuItem("Exit");
in.setMnemonic('N');

jfc=new JFileChooser();
jcc=new JColorChooser();

Container ct=getContentPane();

mf.add(in);
mf.add(io);
mf.add(is);
mf.add(isa);
mf.addSeparator();
mf.add(ie);



    iu=new JMenuItem("Undo");
ip=new JMenuItem("Paste");
ic=new JMenuItem("Copy");
icu=new JMenuItem("Cut");
isal=new JMenuItem("SelectAll");

     cd=new JMenuItem("ColorDialog");
     ce.add(cd);

     in.addActionListener(this);
     io.addActionListener(this);
     is.addActionListener(this);
     isa.addActionListener(this);
     ie.addActionListener(this);


     iu.addActionListener(this);
     ip.addActionListener(this);
     ic.addActionListener(this);
     icu.addActionListener(this);
     isal.addActionListener(this);

     cd.addActionListener(this);

me.add(iu);
me.add(ic);
me.add(ip);
me.add(icu);
me.add(isal);


t=new JTextArea();
jsp=new JScrollPane(t);

ct.add(jsp);
setTitle("Menu");
setSize(300,300);
setVisible(true);
   setExtendedState(JFrame.MAXIMIZED_BOTH);
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae )
{
try{
if(ae.getSource()==in)
{
t.setText("");
}
if(ae.getSource()==ie)
{
System.exit(0);
}
if(ae.getSource()==isal)
{
t.selectAll();
}

if(ae.getSource()==io)
{
jfc.showOpenDialog(this);
try{
                          FileReader fr=new FileReader(jfc.getSelectedFile());
                          BufferedReader br=new BufferedReader(fr);
                          t.setText("");
                          String data="";
                          while((data=br.readLine())!=null)
                          {
 t.append(data+"\n");
}
                           fr.close();
                       }
         catch(Exception e)
            {
            System.out.println("error in reading "+e);
              }

}
if(ae.getSource()==is)
{
jfc.showSaveDialog(this);
try{
                         FileWriter fw=new FileWriter(jfc.getSelectedFile(),true);


                         String data=t.getText();
                        fw.write(data);
                        fw.close();
                }
catch(Exception e)
{
System.out.println("error in writting"+e);
}

        }
        if(ae.getSource()==ic)
        {
t.copy();
}
if(ae.getSource()==icu)
{
t.cut();
}
if(ae.getSource()==ip)
{
t.paste();
}

if(ae.getSource()==cd)
{
Color c=jcc.showDialog(this,"ColorDailog",Color.red);

t.setForeground(c);
}

} catch(Exception e)
{
System.out.println("error is "+e);
}
}
public static void main(String arg[])
{
 new Notepad();
  }
}import mypackage.*;


public class one
{


public static void main (String args[])


{

helloworld h= new helloworld();
 
System.out.println(h.i);

h.print();

}

}
import pack.*;

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


hello h=new hello();

System.out.println(h.i);
}


}import java.io.BufferedReader;
import java.io.InputStreamReader;


public class pal{

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

int no;

BufferedReader br= new BufferedReader (new InputStreamReader(System.in));

System.out.println("enter a number: ");

no=Integer.parseInt(br.readLine());

//System.out.println(no);


int d,s=0,n;
n=no;




while (n>0)
{

d=n%10;

s=(s*10)+d;

n=n/10;

}




//System.out.println(s);


if (no==s)
{

System.out.println("the given number is palindrome");

}

else
{

System.out.println("the given number is not palindrome");
}
}



}
import java.applet.Applet;
import java.awt.Graphics;

/*






*/
public class param extends Applet{

public void init(){


}

public void start(){

}


public void run(){

}

public void paint(Graphics g){

g.drawString("hello",20,30);
String s= getParameter("name");
g.drawString(s,60,80);


}

public void stop(){
}

public void destroy(){
}


}
interface tvstation{

String satellitename="satsun";
String cabletvname="suntv";
double signalfrequency=12.3;
public void show();

}

class programme{

String progname;
String sponser;

programme()
{
progname="debugging";
sponser ="infosys";
}




public void display()
{
System.out.println("\n\nbroadcast display method");
}



}


class broadcast implements tvstation{

String broadcasttime;
String date;

broadcast()
{
broadcasttime="08-30AM";
date="12-nov-2011";

}


public void display()
{
System.out.println("\n\nbroadcast display method");
System.out.println(broadcasttime);
System.out.println(date);
}


public void show()
{
System.out.println("\n\nshow method");
System.out.println(broadcasttime);
System.out.println(date);
System.out.println(satellitename);
System.out.println(cabletvname);
System.out.println(signalfrequency);
}


public static void main(String args[])
{

System.out.println("tvstation program");

broadcast b = new broadcast();

b.display();
b.show();
}



}





















import java.applet.Applet;
import java.net.*;

//  TILE BACKGROUND
//     in the HTML use :
//       PARAM NAME="bgImage" VALUE="images/myImage.jpg"
//     in the APPLET tag

public class Tile extends Applet {
  Image bgImage = null;

  public void init() {
   try {
      MediaTracker tracker = new MediaTracker (this);
      bgImage = getImage
        (new URL(getCodeBase(), getParameter("464502629")));
      tracker.addImage (bgImage, 0);
      tracker.waitForAll();
   }
   catch (Exception e) {
      e.printStackTrace();
   }
   setLayout(new FlowLayout());
   add(new Button("Ok"));
   add(new TextField(10));
  }

  public void update( Graphics g) {
   paint(g);
  }

  public void paint(Graphics g) {
   if(bgImage != null) {
      int x = 0, y = 0;
      while(y < size().height) {
         x = 0;
         while(x< size().width) {
            g.drawImage(bgImage, x, y, this);
            x=x+bgImage.getWidth(null);
            }
         y=y+bgImage.getHeight(null);
      }
   }
   else {
      g.clearRect(0, 0, size().width, size().height);
   }
  }
}import java.util.Random;
public class random{

public static void main(String args[]){

System.out.println("hello world");

Random obj= new Random();

int rgen= obj.nextInt(4)+2;
double rgen1= obj.nextDouble();
System.out.println(rgen);
System.out.println(rgen1);
}

}import java.util.Scanner;



public class Salary{



public static void average(int arr[],int n)
{
float avg;
int s=0;
for (int i=0;i{
s=s+arr[i];

}

avg= s/n;

System.out.println("Average salary is...." +avg );

}




public static void main(String args[])
{

//int name[];

//name
int n;

System.out.println("enter the number of persons: ");

Scanner in= new Scanner(System.in);

n=in.nextInt();

System.out.println(n);


int arr[]= new int [n];


for (int i=0;i{
System.out.println("enter person salary"+ (i+1));
arr[i]= in.nextInt();

}


average(arr,n);


}


}

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

System.out.println("string to array");
String s="abcdeabcdeabcdeqwertqwertqwert";
System.out.println(s);
int n= s.length();
System.out.println(n);
char[] array;
int count=n/5;
System.out.print(count);
array=s.toCharArray();
int j=0;
int tcount=0;
String sarray[]= new String[count];
for(int i=0;i{
sarray[i]="";
}
for(int i=0;i{
if (j==5){
j=0;
tcount++;
}
sarray[tcount]+=array[i];
j++;
}
for(int i=0;i{
System.out.println(sarray[i]);
}


}


}class sqroot implements Runnable{

String str;
int val;

sqroot (String str, int val){
this.str=str;
this.val=val;
}

public void run(){
System.out.println("Runnable process");
System.out.println("square root of first " + val+" "+str  );

for (int i=1;i<=30;i++){
System.out.println("square root of "+i+" is ... "+Math.sqrt(i));

}

}
}


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

System.out.println("sqrt program");


//
sqroot s = new sqroot("natural numbers",30);

//t(s).start();
Thread t= new Thread(s);
t.start();
//new Thread(s).start();
double i=9;
double j;
j= Math.sqrt(i);
System.out.println(j);

}

}class sqroot implements Runnable{

String str;
int val;

sqroot (String str, int val){
this.str=str;
this.val=val;
Thread t= new Thread(this);
t.start();
}

public void run(){
System.out.println("Runnable process");
System.out.println("square root of first " + val+" "+str  );

for (int i=1;i<=30;i++){
System.out.println("square root of "+i+" is ... "+Math.sqrt(i));

}

}
}


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

System.out.println("sqrt program");


//Thread t= new Thread();
sqroot s = new sqroot("natural numbers",30);

//t(s).start();
//new Thread(s).start();
double i=9;
double j;
j= Math.sqrt(i);
System.out.println(j);

}

}import java.net.*;
import java.io.*;


class tcpclient
{
public static void main(String a[]) throws Exception
{
InetAddress ia=InetAddress.getByName("");
Socket cs=new Socket(ia,1003);
}
}


import java.net.*;
import java.io.*;

class tcpserver
{
public static void main(String a[]) throws Exception
{
ServerSocket ss=new ServerSocket(1003);
System.out.println("wating for client");
Socket cs=ss.accept();
System.out.println("connected");
}
}
import java.applet.*;
import java.awt.*;



/*


*/


public class teap extends Applet{

TextField t1,t2;
Color c1;
Button b= new Button("color");

Choice c= new Choice();

public void init(){



//c1= new Color(0.23,0.50,0.80);
t1= new TextField("balaji",10);
t2= new TextField(10);
add(t1);
add(t2);
add(b);
add(c);

c.addItem("one");
c.addItem("two");

}


public void paint(Graphics g){


//setBackground(Color.red);

}

public boolean action(Event e,Object o){
if (e.target instanceof Button)
if(o.equals("color")){
setBackground(Color.red);
b.setLabel("RED");


String s1,s2,s3;
s1=t1.getText();
s2=t2.getText();

int val=30;

//drawString("hello world "+ String.valueOf(val)+s1+s2,40,50);

s3= c.getSelectedItem();

System.out.println(String.valueOf(val)+s1+s2+s3);
return true;}
return false;}

}





import java.util.*;
public class temp {
public static void main (String[] args){
Random generator = new Random();
Scanner sc = new Scanner(System.in);
char[] Email, Username, Password, pass1, user1;
String Name, Surname, Ans;
int age, sqchoice, choice;



System.out.println("Welcome!");
System.out.println("\n[1] Register");
System.out.println("[2] Log in");
System.out.println("[3] Forgot Password/Username");
System.out.println("[4] Quit");
System.out.print("\nEnter your choice: ");
choice = sc.nextInt();
switch(choice){
case 1:
System.out.println("\nKindly enter information below:");
System.out.print("\nName: ");
Name = sc.next();
System.out.print("Surname: ");
Surname = sc.next();
System.out.print("Age: ");
age = sc.nextInt();
System.out.print("Email Address: ");
String input = sc.next();
Email = input.toCharArray();
System.out.print("Username: ");
String input1 = sc.next();
Username = input1.toCharArray();
System.out.print("Password: ");
String input2 = sc.next();
Password = input2.toCharArray();
System.out.println("\nSecurity Questions: ");
System.out.println("[1] What was your childhood nickname?");
System.out.println("[2] What is the name of your favorite childhood friend?");
System.out.println("[3] What is your maternal grandmother's maiden name?");
System.out.println("[4] What is your oldest cousin's first and last name?");
System.out.print("\nEnter your choice: ");
sqchoice = sc.nextInt();
System.out.print("\nAnswer: ");
Ans = sc.next();
int number = generator.nextInt(1000000) + 1;
System.out.println("\nYour Unique Number: "+number);
case 2:
System.out.print("\nUsername: ");
String input3 = sc.next();
user1 = input3.toCharArray();
System.out.print("Password: ");
String input4 = sc.next();
pass1 = input4.toCharArray();
if ((Arrays.equals(Username,user1)) && (Arrays.equals(Password,pass1))){
System.out.print("WIN");
}else{
System.out.print("FAIL");
}

break;


}
}
}import java.lang.Runtime;
import java.lang.*;
import java.io.*;
import java.io.Console;


public class test1{

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


System.out.println("run time path");


//System.out.println(System.getenv("Path"));
//Process process = Runtime.getRuntime().exec("notepad.exe");

Runtime r= Runtime.getRuntime();
//Process p = Runtime.getRuntime.exec("cmd /c dir");
//Process p1=r.exec("F:\\Contacts_New_Updated.xls");//working fine
//Process p2=r.exec("cls");//working fine
//Process p3=r.exec("test1.java");//cannot run
//Process p4=r.exec("dir");// cannot run
//ProcessBuilder p = new ProcessBuilder("cmd.exe", "/C", "dir");



 //ProcessBuilder l = new ProcessBuilder();
//l.command("dir");
 //Process p = launcher.start(); //


try {
         Process p = new ProcessBuilder("cmd.exe", "/C", "dir").redirectErrorStream(true).start();
         InputStream is = p.getInputStream();
         BufferedReader br = new BufferedReader(new InputStreamReader(is));
         String in;
         while ((in = br.readLine()) != null) {
            System.out.println(in);
         }
      }catch(Exception e) {
         e.printStackTrace();
      }


}

 Console cons = System.console();
//System.console.clear();

 // Will create a new process
//Process ps=Runtime.getRuntime().exec (new String[]{"cmd","/c","cls"});
// ps.waitFor();

}import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Label;
import java.awt.TextField;
import java.awt.Color;
import java.lang.Thread;
import java.util.Date;
/*




*/

public class testap1 extends Applet implements Runnable{

Label l;
TextField t;
Date d;
Color c;

Thread t1;
public void init(){

t1= new Thread(this);

t1.start();


l= new Label("user name: ");

add(l);

t= new TextField(20);

add(t);

}


public void run(){

while(true){

c= new Color((float)Math.random(),(float)Math.random(),(float)Math.random());

repaint();
try{
Thread.sleep(2000);

}
catch(InterruptedException e){


}

}

}


public void paint(Graphics g){

d= new Date();

g.drawString(d.toString(),10,50);

System.out.println(d);
setBackground(c);
showStatus("hello program");
g.drawString("hello",50,50);

g.drawLine (50,50,150,50);

}
}import java.net.*;
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Font;
import java.awt.Button;
import java.awt.Label;
import java.awt.Image;
import java.util.Date;

/*

*/
public class testapplet extends Applet implements Runnable{

//URL i;
Image i;
Label l;

Thread t;

Date d;

public void init(){

l= new Label("hello");

add (l);
System.out.println("applet initiated");

setBackground(Color.red);


Button en= new Button("welcome");

this.add(en);

i= getImage(getDocumentBase(),"4.jpg");
//i=
}


public void start()
{

t= new Thread(this);
t.start();
System.out.println("applet started");
repaint();
}

public void run()
{

while(true){
System.out.println("applet run");
repaint();
//setBackground(Color.blue);

try{
Thread.sleep(1000);


}
catch(InterruptedException e){}

}

}


public void paint(Graphics g)
{

d= new Date();
g.drawString(d.toString(),30,30);

Font f = new Font("TimesRoman",Font.BOLD,28);
g.setFont(f);

g.setColor(Color.blue);
setBackground(Color.GRAY);
System.out.println("applet painted");
//g.drawString("\n\n\n\nits my first applet",30,30);
g.drawRect(20,10,240,30);
//int n= g.getStyle(f);
//System.out.println(n);

g.drawImage(i,0,0,900,600,this);
}

}import java.net.DatagramSocket;
import java.net.InetAddress;

public class udpclient
{
        public static void main(String args[])
        {
                try
                {
                        String server_address = "localhost";
                        int server_port = 1111;
                        String message = "hello akshay";

                        InetAddress address = InetAddress.getByName(server_address);
DatagramPacket packet = new DatagramPacket(message.getBytes(),message.getBytes().length, address, server_port);                                                  

                     
                        DatagramSocket socket = new DatagramSocket();
                        socket.send(packet);
                        System.out.println("UDPClient: Sent data to Server ; Message = " + message);
                        socket.close();
                }
                catch (Exception e)
                {
                        e.printStackTrace();
                        System.out.println("Error in sending the Data to UDP Server");
                }
        }
}
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class udpserver
{
        public static void main(String args[])
        {
                int server_port = 1111;
                System.out.println("UDP try to connect " + server_port);
                try
                {
                        DatagramSocket socket = new DatagramSocket(server_port);
                        byte[] msgBuffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(msgBuffer, msgBuffer.length);

                        while (true)
                        {
                                socket.receive(packet);
                                String message = new String(msgBuffer, 0, packet.getLength());
                                System.out.println("UDPServer: Message received = " + message);
                                packet.setLength(msgBuffer.length);
                        }
                }
                catch (Exception e)
                {
                        e.printStackTrace();
                        System.out.println("Error in getting the Data from UDP Client");
                }
        }
}
interface teleinformation{
String tvname="samsung";
double price=16400.00;
public void showdetails();
}




class Broadcast1  {
String broadcasttime;
String date;
Broadcast1()
{
broadcasttime="08-30AM";
date="12-nov-2011";
}
public void display()
{
System.out.println("\n\nbroadcast display method");
System.out.println(broadcasttime);
System.out.println(date);
}
public void show()
{
System.out.println("\n\nshow method");
System.out.println(broadcasttime);
System.out.println(date);
}
}


class viewer extends Broadcast1 implements teleinformation
{


public void showdetails(){
System.out.println(broadcasttime);
System.out.println(date);
System.out.println(tvname);
System.out.println(price);

}

public static void main(String args[])
{

System.out.println("viewer program");

viewer v = new viewer();

v.display();
v.show();
v.showdetails();

}

}





/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package browser;

/**
 *
 * @author Tom
 */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;

public class Browser {
    private JFrame frame;
    private JPanel panelTop;
    private JEditorPane editor;
    private JScrollPane scroll;
    private JTextField field;
    private JButton button;
    private URL url;

    public Browser(String title) {
        initComponents();

        //set the title of the frame
        frame.setTitle(title);

        //set the default cloe op of the jframe
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //set size of frame
        frame.setSize(800,600);

        //add jpanel to north of jframe
        frame.add(BorderLayout.NORTH, panelTop);

        //add textfield and navigation button to jpanel.
        panelTop.add(field);
        panelTop.add(button);

        //add scroll pane to jframe center
        frame.add(BorderLayout.CENTER, scroll);

       
        //set the frame visible
        frame.setVisible(true);
    }//end Browser() constructor

    private void initComponents() {
        //create the JFrame
        frame = new JFrame();

        //create the JPanel used to hold the text field and button.
        panelTop = new JPanel();
       
        //set the url
        try {
            url = new URL("http://www.javagaming.org");
        }
        catch(MalformedURLException mue) {
            JOptionPane.showMessageDialog(null,mue);
        }
       
        //create the JEditorPane
        try {
            editor = new JEditorPane(url);
           
            //set the editor pane to false.
            editor.setEditable(false);
        }
        catch(IOException ioe) {
            JOptionPane.showMessageDialog(null,ioe);
        }
       
        //create the scroll pane and add the JEditorPane to it.
        scroll = new JScrollPane(editor, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

        //create the JTextField
        field = new JTextField();

        //set the JTextField text to the url.
        //we're not doing this on the event dispatch thread, so we need to use
        //SwingUtilities.
        SwingUtilities.invokeLater(new Runnable() {
           public void run() {
               field.setText(url.toString());
           }
        });

        //create the button for chanign pages.
        button = new JButton("Go");
       
        //add action listener to the button
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    editor.setPage(field.getText());
                }
                catch(IOException ioe) {
                    JOptionPane.showMessageDialog(null, ioe);
                }
            }
        });
    }//end initComponents()

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Browser("Simple web browser");
            }
        });
    }//end main method.
}//end Browser class
Any question, pleimport java.net.*;
import java.awt.*;
import java.awt.event.*;
import com.sun.java.swing.*;
import java.io.*;

//The main class
public class voyagers implements ActionListener,Runnable
{
 public  final int SCROLLBARS_VERTICAL_ONLY = 1;
 Thread thread;
 String resource, host, file, url, ReloadReaderCount;
 String PrevFileContents,NextFileContent, FileGoGetter;
 HTTP webconnect;
 TextField textfield;
 Frame frame;
 TextArea textarea;
 JButton back,forward,home,stop,reload;
 MenuItem open,save,exits;
 int Eternal=2;
 int TextAreaFileNameContent,SavedFileReaderCount;
 int urlLength,slash,count,increment;

//The first function to be called.
//It creates an object that looks like the voyagers class.
public static void main(String s[])
{
     voyagers MyBrowser=new voyagers();
     MyBrowser.Intializer();
}

//This is the initialization method.
//It initializes the various components of the interface.
public void Intializer()
{
 File creator=new File("UrlHistory");
 creator.mkdir();
 File OldFiles=new File("UrlHistory\\");
 String ListOfOldFiles[] = OldFiles.list();
 int NumberOfOldFiles = ListOfOldFiles.length;
 for(int OldFilesCount=0; OldFilesCount< NumberOfOldFiles; OldFilesCount++)
  {
     File DeleteFiles=new File("UrlHistory\\" + ListOfOldFiles[OldFilesCount]);
     DeleteFiles.delete();
  }
 frame = new Frame("VOYAGER");
 frame.setLayout(new BorderLayout());
 textfield=new TextField("127.0.0.1",20);
 textarea =new TextArea("",10,50,SCROLLBARS_VERTICAL_ONLY);
 textarea.setEditable(false);
 MenuBar menubar=new MenuBar();
 Menu menu = menubar.add(new Menu("File"));
 open = (MenuItem)menu.add(new MenuItem("Open"));
 open.addActionListener(this);
 save = (MenuItem)menu.add(new MenuItem("Save"));
 save.addActionListener(this);
 exits = (MenuItem)menu.add(new MenuItem("Exit"));
 exits.addActionListener(this);
 menubar.add(menu);
 JToolBar toolbar = new JToolBar();
 back = (JButton)toolbar.add(new JButton("      <<= Back     "));
 back.addActionListener(this);
 back.setEnabled(false);
 forward = (JButton)toolbar.add(new JButton("   =>> Forward    "));
 forward.addActionListener(this);
 forward.setEnabled(false);
 home = (JButton)toolbar.add(new JButton("     <<=>>Home     "));
 home.addActionListener(this);
 stop = (JButton)toolbar.add(new JButton("       << Stop >>     "));
 stop.addActionListener(this);
 stop.setEnabled(false);
 reload = (JButton)toolbar.add(new JButton(" <<=>>  Reload <<=>>"));
 reload.addActionListener(this);
 reload.setEnabled(false);
 frame.add(toolbar,"North");
 frame.add(textfield,"South");
 textfield.addActionListener(this);
 frame.add(textarea,"Center");
 frame.setMenuBar(menubar);
 frame.resize(650,450);
 frame.show();
 HomePage();
 }
           
//This  method  is self-explanatory.
//It traps all actions performed by the user on the
//various components of the application.
public void actionPerformed(ActionEvent e)  
 {
//This if condition is satisfied whenever any
//action is performed on the  textfield component.
  if(e.getSource() == textfield)
   {
    url = ((TextField)e.getSource()).getText();
    urlLength = url.length();
    thread=new Thread(this);
    thread.start();
   }

//This condition is satisfied whenever the
//user clicks on the  back button on the user interface
  else
  if(e.getSource() == back)
 {

   {
    increment =increment - 1;
    if(increment == 1 || increment == 0)
    back.setEnabled(false);
    String TextAreaContent=textarea.getText();
    int TextAreaContentLength=TextAreaContent.length();
    textarea.replaceText("",0,TextAreaContentLength);
    forward.setEnabled(true);
     try
      {
       BufferedReader PrevFile = new BufferedReader(new FileReader("UrlHistory\\one"+increment+".html"));
        while((PrevFileContents=PrevFile.readLine())!= null)
         {
          textarea.append(PrevFileContents);
         }
      }
     catch (Exception ex)
      {
      }
   }
 
//This condition is satisfied whenever the
//user clicks on the forward button on the user interface
  else
  if(e.getSource() == forward)
 {

    back.setEnabled(true);
    String PrevFilesContentsDeleter=textarea.getText();
    int PrevFilesContentsDeleterLength=PrevFilesContentsDeleter.length();
    textarea.replaceText("",0,PrevFilesContentsDeleterLength);
     try
      {
       increment = increment+1;
       BufferedReader NextFile = new BufferedReader(new FileReader("UrlHistory\\one"+increment+".html"));
        while((NextFileContent=NextFile.readLine())!= null)
         {
          textarea.append(NextFileContent);
         }
        if (increment == count)
         forward.setEnabled(false);
      }
     catch (Exception ex)
      {
      }
   }
 
//This condition is satisfied whenever the
//user clicks on the home button on the interface
  else
  if(e.getSource() == home)
   {

    String ScreenCleaner=textarea.getText();
    int ScreenCleanersLength=ScreenCleaner.length();
    textarea.replaceText("",0,ScreenCleanersLength);
     try
      {
       int HomePageReaderCount;
       String HomeIPAddress="127.0.0.1";
       HTTP HomePageProtocol=new HTTP(HomeIPAddress);
       String DefaultFile="\\";
       String DefaultFileReaderString;
       InputStream HomePageReader = HomePageProtocol.get(DefaultFile);
       OutputStream  HomePageSaver=new FileOutputStream("UrlHistory\\one.html");
        while((HomePageReaderCount = HomePageReader.read()) != -1)
         {
          HomePageSaver.write((char)HomePageReaderCount);
         }
       BufferedReader HomePageWriter = new BufferedReader(new FileReader("UrlHistory\\one.html"));
        while((DefaultFileReaderString=HomePageWriter.readLine())!= null)
         {      
          textarea.append(DefaultFileReaderString);
         }
      }
     catch (Exception s)
      {
       ExceptionHandler b = new ExceptionHandler();
       b.ServerDown();
      }
   }

//This condition is satisfied whenever the
//user clicks on the stop button of the interface
  else
  if(e.getSource() == stop)
   {
    stop.setEnabled(false);
    thread.stop();
   }
 
//This condition is satisfied whenever the
//user clicks on the reload button on the interface
  else
  if(e.getSource() == reload)
   {

    url = textfield.getText();
    urlLength = url.length();
     try
      {
       resource=url.substring(0);
       slash=resource.indexOf('/');
       file=resource.substring(slash);
       host=resource.substring(0,slash);
       webconnect=new HTTP(host);
        if(webconnect!=null)
         {
          count = count +1;
          increment = count;
          forward.setEnabled(false);
          InputStream TextAreaFileName = webconnect.get(file);
          OutputStream  TextAreaFileNameSaver=new FileOutputStream("UrlHistory\\one"+increment+".html");
           while((TextAreaFileNameContent= TextAreaFileName.read()) != -1)
            {
             TextAreaFileNameSaver.write((char)TextAreaFileNameContent);
            }
          String Blanker=textarea.getText();
          int BlankerSize=Blanker.length();
          textarea.replaceText("",0,BlankerSize);
          BufferedReader ReloadReader = new BufferedReader(new FileReader("UrlHistory\\one"+increment+".html"));
           while((ReloadReaderCount=ReloadReader.readLine())!= null)
            {
             back.setEnabled(true);
             textarea.append(ReloadReaderCount);
             }
         }
      }
               catch(StringIndexOutOfBoundsException io)
               {
                ExceptionHandler b = new ExceptionHandler();
                b.PutSlash();
               }
               catch(FileNotFoundException r)
               {
               }
               catch(UnknownHostException h)
               {
               ExceptionHandler b = new ExceptionHandler();
               b.ServerDown();
               }
               catch(IOException o)
               {
               ExceptionHandler b = new ExceptionHandler();
               b.ServerDown();
               }      
  }
 
//This condition is satisfied whenever the
 //the user selects the menuoption open.
  else
  if (e.getSource() == open)
   {

    String Disintegrator=textarea.getText();
    String directory;
    int DisintegratorLength=Disintegrator.length();
    textarea.replaceText("",0,DisintegratorLength);
    Frame OpenFrame=new Frame("open");
    FileDialog filedialog=new FileDialog(OpenFrame,"parameter",0);
    filedialog.show();
    directory=filedialog.getDirectory();
    FileGoGetter=filedialog.getFile();
     try
      {
       int FileOnDiskSize;
       String FileOnDiskReader;
       InputStream FileOnDisk=new FileInputStream(directory+FileGoGetter);
       OutputStream FileOnDiskSaver=new FileOutputStream("UrlHistory\\parag.html");
        while((FileOnDiskSize = FileOnDisk.read()) != -1)
         {
          FileOnDiskSaver.write((char)FileOnDiskSize);
         }
       BufferedReader FileOnDiskWriter = new BufferedReader(new FileReader("UrlHistory\\parag.html"));
        while((FileOnDiskReader = FileOnDiskWriter.readLine())!= null)
         {
          textarea.append(FileOnDiskReader);
         }
      }
     catch(IOException io)
       {
       }  
   }

//This condition is satisfied whenever the
//the user selects the menuoption save.
  else
  if (e.getSource() == save)
   {

    String p=new String();
    Frame SaveFrame=new Frame("frames");
    FileDialog SaveFileDialog=new FileDialog(SaveFrame,"p",1);
    SaveFileDialog.show();
    String SavedFileName;
    String SavedFileDirectory;
    SavedFileDirectory=SaveFileDialog.getDirectory();
    SavedFileName=SaveFileDialog.getFile();
     try
      {
       FileInputStream SavedFileReader=new FileInputStream("UrlHistory\\one"+increment+".html");
       FileOutputStream SavedFileWriter=new FileOutputStream(SavedFileDirectory+SavedFileName);
        while(( SavedFileReaderCount= SavedFileReader.read())!= -1)
         {
           SavedFileWriter.write((char)SavedFileReaderCount);
         }
      }
     catch(IOException io)
      {
      }
   }

//This condition is satisfied whenever the
//the user selects the menuoption exit.
  else
  if (e.getSource() == exits)
   {

    System.exit(0);
   }
 }

//This method is called whenever the user performs
//any action on the textfield component.This method starts
//by finding out the name of the file to be fetched from the server.
//It then connects to the server and gets the file requested by the user.

public void run()
 {
  try
   {
    resource=url.substring(0);
    slash=resource.indexOf('/');
    file=resource.substring(slash);
    host=resource.substring(0,slash);
    webconnect=new HTTP(host);
     if(webconnect!=null)
      {
       count = count +1;
       increment = count;
       InputStream WWWFileReader = webconnect.get(file);
       OutputStream WWWFileWriter=new FileOutputStream("UrlHistory\\one"+increment+".html");
        while((TextAreaFileNameContent= WWWFileReader.read()) != -1)
         {
          WWWFileWriter.write((char)TextAreaFileNameContent);
         }
       BufferedReader WWWScreenWriter = new BufferedReader(new FileReader("UrlHistory\\one"+increment+".html"));
       String WWWScreenCleaner=textarea.getText();
       int WWWScreenCleanerSize=WWWScreenCleaner.length();
       textarea.replaceText("",0,WWWScreenCleanerSize);
        while((ReloadReaderCount=WWWScreenWriter.readLine())!= null)
         {
          forward.setEnabled(false);
          stop.setEnabled(true);
          reload.setEnabled(true);
          textarea.append(ReloadReaderCount);
           if(count == 2)
            back.setEnabled(true);
         }
      }
   }
  catch(IOException io)
   {
    ExceptionHandler b = new ExceptionHandler();
    b.ServerDown();
   }
 }
//This method is called explicitly to get the homepage
//from the localhost machine.It connects to the server running
//on the same machine as this application and gets it's default
//html file.
public void HomePage()
 {
  if(Eternal == 2)
   {
    int OurDefaultFileCount;
     try
      {
       count=1;
       increment=count;
       String Ourselves="127.0.0.1";
       HTTP OurUrl=new HTTP(Ourselves);
       String OurDefaultFile="\\";
       String DefaultFileStringReader;
       InputStream OurDefaultFileReader = OurUrl.get(OurDefaultFile);
       OutputStream OurDefaultFileWriter=new FileOutputStream("UrlHistory\\one"+increment+".html");
        while((OurDefaultFileCount= OurDefaultFileReader.read()) != -1)
         {
          OurDefaultFileWriter.write((char)OurDefaultFileCount);
         }
       BufferedReader DefaultFileScreenWriter = new BufferedReader(new FileReader("UrlHistory\\one"+increment+".html"));
        while((DefaultFileStringReader=DefaultFileScreenWriter.readLine())!= null)
         {
          textarea.append(DefaultFileStringReader);
         }
      }
     catch (Exception e)
      {
       ExceptionHandler b = new ExceptionHandler();
       b.ServerDown();
      }
    Eternal=3;
   }
 }
}


//This is the class which has the actual code for getting
//connected to any server.
class HTTP
{
 public final static int HTTP_PORT=80;
 InetAddress wwwserver;
 DataInputStream FinalReader;
 PrintStream FinalPrinter;
 String response;
//This constructor is called automatically whenever any
//object of the said class is created. This constructor performs a simple
//thing.It gets the name of the server machine from which
//the html file has to be fetched.
 public HTTP(String Server) throws UnknownHostException
  {
   wwwserver=InetAddress.getByName(Server);
  }
//This method gets the html file from the server. It creates
//a socket which is then used to get connected to the server
//machine.Once connected,it makes use of the stream classes
//to get the contents of the html file.
 public InputStream get(String filename) throws IOException
  {
   Socket socket;
   InputStream InitialReader;
   OutputStream InitialWriter;
   socket= new Socket(wwwserver,HTTP_PORT);
    if(socket==null)
     {
      return null;
     }
   InitialReader=socket.getInputStream();
   InitialWriter=socket.getOutputStream();
   FinalReader=new DataInputStream(InitialReader);
   FinalPrinter=new PrintStream(InitialWriter);
    if(InitialReader==null || InitialWriter==null)
     {
      return null;
     }
   FinalPrinter.println("GET " + filename + " HTTP/1.0\n");
    while((response=FinalReader.readLine()).length() > 0)
     {
      if(response.startsWith("HTTP/1.0 404 Not Found"))
       {
        ExceptionHandler ErrorFile=new ExceptionHandler();
        ErrorFile.FileNotFound();
       }
     }
   return FinalReader;
  }
}
//This class declares the functions which implement native code
//These functions are called whenever an exception occurs and a
//MessageBox with an appropriate error message is displayed.
class ExceptionHandler
 {                          
 public native void ServerDown();
 public native void FileNotFound();
 public native void PutSlash();
//This constructor loads the new.dll which contains
//the actual code for the above mentioned functions.
 public ExceptionHandler()
  {
   System.loadLibrary("new");
  }
 }



//End of the Java Browser.import java.net.URL;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JEditorPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.event.HyperlinkListener;
import javax.swing.event.HyperlinkEvent;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Color;

import java.io.IOException;

/**
 * simple demo for a web browser
 *
 * @author Stefano Markidis
 *
 */
public class WEBbrowser extends JFrame implements HyperlinkListener,
ActionListener{
public static void main(String[] args) {
// take the initial web page from the command line argument
if (args.length == 0)
 new WEBbrowser("http://www.cs.unm.edu/");
else
 new WEBbrowser(args[0]);
}
private JTextField urlField;
private JEditorPane htmlPane;
private String initialURL;

    public WEBbrowser(String initialURL) {
super("Simple Browser");
this.initialURL = initialURL;
// add a listener to the window for closing init
addWindowListener(new ExitListener());
// add a top panel
JPanel topPanel = new JPanel();
topPanel.setBackground(Color.green);
// create a Jlabel and JTextField for gettingURL
JLabel urlLabel = new JLabel("URL:");
urlField = new JTextField(30);
urlField.setText(initialURL);
// add a listener to JTextField
urlField.addActionListener(this);

// add url label and field to toppanel
topPanel.add(urlLabel);
topPanel.add(urlField);

//add top panel at the top and html text at the center
getContentPane().add(topPanel, BorderLayout.NORTH);
try {
htmlPane = new JEditorPane(initialURL);
htmlPane.setEditable(false);
htmlPane.addHyperlinkListener(this);
JScrollPane scrollPane = new JScrollPane(htmlPane);
getContentPane().add(scrollPane, BorderLayout.CENTER);
} catch(IOException ioe) {
  System.out.println("Can't build HTML pane for " + initialURL);
}
Dimension screenSize = getToolkit().getScreenSize();
int width = screenSize.width * 8 / 10;
int height = screenSize.height * 8 / 10;
setBounds(width/8, height/8, width, height);
setVisible(true);
 }
 // event handling for changing the URL
 public void actionPerformed(ActionEvent event) {
String url;
url = urlField.getText();
try {
 htmlPane.setPage(new URL(url));
 urlField.setText(url);
} catch(IOException ioe) {
 System.out.println("Can't follow link to " + url );
}
 }
 // event handling when you click on a link
 public void hyperlinkUpdate(HyperlinkEvent event) {
if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
 try {
htmlPane.setPage(event.getURL());
urlField.setText(event.getURL().toExternalForm());
 } catch(IOException ioe) {
System.out.println("Can't follow link to "
+ event.getURL().toExternalForm() );
 }
}
 }
 }

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.IDN;

import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;

public class WebBrowserBasedOnJEditorPane extends JFrame implements HyperlinkListener {
  private JTextField txtURL= new JTextField("");
  JEditorPane ep = new JEditorPane();
  private JLabel lblStatus= new JLabel(" ");

  public WebBrowserBasedOnJEditorPane() {
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    JPanel pnlURL = new JPanel();
    pnlURL.setLayout(new BorderLayout());
    pnlURL.add(new JLabel("URL: "), BorderLayout.WEST);
    pnlURL.add(txtURL, BorderLayout.CENTER);
    getContentPane().add(pnlURL, BorderLayout.NORTH);
    getContentPane().add( ep, BorderLayout.CENTER);

    getContentPane().add(lblStatus, BorderLayout.SOUTH);

    ActionListener al = new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        try {
          String url = ae.getActionCommand().toLowerCase();
          if (url.startsWith("http://"))
            url = url.substring(7);
          ep.setPage("http://" + IDN.toASCII(url));
        } catch (Exception e) {
          e.printStackTrace();
          JOptionPane.showMessageDialog(WebBrowserBasedOnJEditorPane.this, "Browser problem: " + e.getMessage());
        }
      }
    };
    txtURL.addActionListener(al);

    setSize(300, 300);
    setVisible(true);
  }
  public void hyperlinkUpdate(HyperlinkEvent hle) {
    HyperlinkEvent.EventType evtype = hle.getEventType();
    if (evtype == HyperlinkEvent.EventType.ENTERED)
      lblStatus.setText(hle.getURL().toString());
    else if (evtype == HyperlinkEvent.EventType.EXITED)
      lblStatus.setText(" ");
  }

  public static void main(String[] args) {
    new WebBrowserBasedOnJEditorPane();
  }
}import java.io.*;
import java.util.Scanner;
class wrongmarkexception extends Exception{

public wrongmarkexception(String str)
{

super(str);


}



}


public class wmexception{

int smark[]= new int[20];

public  void cal()throws wrongmarkexception
{
System.out.println("enter twenty students marks: ");
Scanner in= new Scanner(System.in);
for (int i=0;i<5 i="" p="">{
smark[i]=in.nextInt();
if ((smark[i]<0 i="" smark="">100))
throw new wrongmarkexception ("invalid mark");
}


for (int i=0;i<5 i="" p="">{
System.out.println("Student mark details" + smark[i]);
}

}



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


System.out.println("wrong mark exception");

wmexception w = new wmexception();
try{

w.cal();
}

catch(wrongmarkexception e){

System.out.println("exception is .."+ e);

}

}
}

No comments:

Post a Comment

உப்பு மாங்காய்

சுருக்குப்பை கிழவி. சுருக்கங்கள் சூழ் கிழவி. பார்க்கும் போதெல்லாம் கூடையுடனே குடியிருப்பாள். கூடை நிறைய குட்டி குட்டி மாங்காய்கள். வெட்டிக்க...