Java Progs

71
ASSIGNMENT-1: 1.1 Set the following variables used in java in windows environment (i) JAVA_HOME (ii) CLASSPATH (iii) PATH Solution Start your System panel (Start > Settings > Control Panel > System). If you see Advanced or Environment, click those. There are two windows on this panel: System variables and User variables. Check whether you have a Set button or a new button. If you see a Set button:

Transcript of Java Progs

Page 1: Java Progs

ASSIGNMENT-1:1.1 Set the following variables used in java in windows environment

(i) JAVA_HOME(ii) CLASSPATH(iii) PATH

Solution Start your System panel (Start > Settings > Control Panel > System). If you see Advanced or Environment, click those. There are two windows on this panel: System variables and User variables.

Check whether you have a Set button or a new button. If you see a Set button:

Do not click the Set button.

Click on ANY item in the User variables list. The Variable and Value fields are then filled in with whatever item you clicked.

Replace the expression in the Variable field with the single word PATH.

Replace the expression in the Value field with the following (where you should use replace "j2sdk1.4.1_01" with whatever directory name is correct for your installation of java):

%path%;c:\j2sdk1.4.1_01\bin

Click both Set and Apply, in that order.

Now replace the expression in the Variable field with the single word CLASSPATH.

Replace the expression in the Value field with this:

%classpath%;.

Click both Set and Apply, in that order.

Exit all windows and programs, especially any command prompt window. Try the java and javac commands again to see if they work now. If they do not, restart your computer and try the java and javac commands again.

If you see a New button and not a Set button: Click New. In the Name field, type PATH. In the Value field, type the following (where you should use replace

"j2sdk1.4.1_01" with whatever directory name is correct for your installation of java):

%path%;c:\j2sdk1.4.1_01\bin Click OK to complete that variable. Click in the User variables window. Click New and create a variable named CLASSPATH with the following value: %classpath%;. Click OK to complete that variable.

Page 2: Java Progs

Exit all windows and programs, especially any command prompt window. Try the java and javac commands again to see if they work now. If they do not, restart your computer and try the java and javac commands again.

Page 3: Java Progs

1.2 Write down a program in Java using notepad to display “HELLO WORLD” and mention all the steps used in compiling and running the program.Solution:

public class Hello{

public static void main(String arg[]){

System.out.println(“HELLO WORLD”);}

}

// SAVE THE FILE AND OPEN CONSOLE WINDOW/DOS TO RUN THE PROGRAM// to compile the file Hello.java use the following commandC:\JDK5.0\BIN> javac Hello.java// to run the file java interpreter is use .class file which is designed after successful compilation. To run following instruction should be typed.C:\JDK5.0\BIN> java Hello

Output:HELLO WORLD

Page 4: Java Progs

ASSIGNMET-22.1 Write a program in Java to calculate the factorial of a number given by the

user. Take the number input using command line arguments.Solution:

class fact{

public static void main(String arg[]){

int n= Integer.parseInt(arg[0]);int fact=1,i;for(i=n;i>=1;i--){

fact=fact*i;}System.out.println("\n Factorial of given number is = " +

fact);}

}Output:

// compile as followingJavac fact.java// run the followingJava fact 4Factorial of given number is = 24

Page 5: Java Progs

2.2 Write a program in Java to print FIBONACCI series. Take the number of terms in series input from user using command line arguments.

Solution:class Fibo{

public static void main(String arg[]){

int n= Integer.parseInt(arg[0]);int a=0,b=1,c=1,i;for(i=0;i<n;i++){

System.out.println(c);c=a+b;a=b;b=c;

}}

}Output:

// compile & execute using following commandsJavac Fibo.javaJava Fibo 6112358

Page 6: Java Progs

2.3 Write a program in Java to print the following pattern. * * *

* * * * * * * * * *

* * *

class Pattern{

public static void main(String arg[]){

int n= Integer.parseInt(arg[0]);int i,s,sp;for(i=1;i<n;i++){

System.out.println();for(sp=i;sp<=n;sp++){

System.out.print(" ");}for(s=i;s<=i;s++){

System.out.print("* ");}

}for(i=n;i>=1;i--){

System.out.println();for(sp=i;sp<=n;sp++){

System.out.print(" ");}for(s=1;s<=i;s++){

System.out.print("* ");}

}}

}

OUTPUT:Javac Pattern.javaJava Pattern 6

*

Page 7: Java Progs

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

Page 8: Java Progs

ASSIGNMENT-33.1 Create an abstract class called shape in package shapes with abstract methods area, circumference, set, print.

SOLUTION:package shapes;

public abstract class shapes {

public float r,ar,cr;/** * @param args */

public abstract void area();public abstract void circumfrence();public abstract void set(float r);public abstract void print();

}

Page 9: Java Progs

3.2 Define a circle class in package shapes, including the instance variable named radius and the following methods: Area, circumference, set, print and others needed.

SOLUTIONpackage shapes;import java.lang.Math;public class circle extends shapes {

/** * @param args */

public void area(){

ar=(float)Math.PI*r*r;

}public void circumfrence(){

cr=2*(float)Math.PI*r;}public void set(float a){

r=a;}public void print(){

System.out.println("radius of circle is " + r);System.out.println("area of circle " + ar);System.out.println("circumfrence of circle " + cr);

}}

Page 10: Java Progs

3.3 Based on the circle class, write a driver class in package client to set the value of radius of a circle and output its area and circumference.

SOLUTIONpackage client;import shapes.*;import java.util.*;public class driver {/** * @param args */

public static void main(String[] args) {// TODO Auto-generated method stub

Scanner s1=new Scanner(System.in);float f1=Float.parseFloat(s1.next());circle c1=new circle();c1.set(f1);c1.area();c1.circumfrence();c1.print();

}}

OUTPUT:6.0radius of circle is 6.0area of circle 113.097336circumfrence of circle 37.699112

3.4 Input an e-mail id and check whether the input e-mail id is valid or not. Use command line arguments.

SOLUTION:package email;

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

String ch=args[0];ch=ch.toLowerCase();System.out.println(ch);int aa=ch.indexOf('@');

if(ch.indexOf('@')!=ch.lastIndexOf('@') || ch.indexOf('@')==-1){

System.out.println("invalid");System.exit(0);

}

Page 11: Java Progs

else if((ch.length()-(ch.lastIndexOf('.')+1))<2 || (ch.length()-(ch.lastIndexOf('.')+1))>3)

{System.out.println("invalid");System.exit(0);

}else if(ch.charAt(0)<'a' || ch.charAt(0)>'z'){

System.out.println("invalid");System.exit(0);

}int len=ch.length();for(int i=0;i<len;i++){

if(ch.charAt(i)>='a' && ch.charAt(i)<='z'){

continue;}else if(ch.charAt(i)>=48 && ch.charAt(i)<=57){

continue;}else if(ch.charAt(i)=='.')

continue;

else if(ch.charAt(i)=='_')continue;

else if(ch.charAt(i)=='@')continue;

else{

System.out.println("invalid");System.out.println(ch.charAt(i));System.out.println(ch.indexOf(i));System.out.println(aa);System.exit(0);

}}

}}

OUTPUT:Javac email.javaJava email [email protected][email protected]

Page 12: Java Progs

3.5 Find length for a given string use command line argument. Convert this string into an array. Replace all characters at even places with a special symbol # and display

package string;

public class string {

public static void main(String args[]){

int j=0;String str=new String();str=args[0];char str1[];str1=str.toCharArray();System.out.println(str1);for(int i=0;i<str.length();i++){

if((i+1)%2==0)str1[i]='#';

j=j+1;}System.out.println("length of string is "+ j);for(int i=0;i<str.length();i++)

System.out.print(str1[i]);}

}

OUTPUT:sahillength of string is 5s#h#l

Page 13: Java Progs

ASSIGNMENT-4 To determine number of strings passed in command line argument and

find all the occurrences of last command line input in the concatenated string.

SOLUTION:package string;

public class stringmatch {

/** * @param args */

public static void main(String[] args) {// TODO Auto-generated method stub//String s1=new String();

int len,count=0,flag=0;len=args.length;for(int i=0;i<len-1;i++){

if(args[i].toLowerCase().equals(args[len-1].toLowerCase())){

flag=1;System.out.println("last string occurs at index "+ (i+1));count++;

}}if(flag>0)

System.out.println("last string occurs "+ (count+1) +" times in passed strings and no of strings passed is "+ len);

elseSystem.out.println("last string doesn't repeat in the passed

strings");

}

OUTPUT:last string doesn't repeat in the passed strings

Page 14: Java Progs

4.2 To check whether a given string is valid integer or not. Use command line arguments.

SOLUTION:package string;

public class integer {

/** * @param args */

public static void main(String[] args){// TODO Auto-generated method stubString s1=new String();s1=args[0];int len=s1.length();for(int i=0;i<len;i++){

if(s1.charAt(i)<48 || s1.charAt(i)>57){

System.out.println("the entered string is not a valid integer");

System.exit(0);}

}Double d1=Double.parseDouble(args[0]);if(d1<-2147483648 || d1>2147483647)

System.out.println("the entered string is not a valid integer");else

System.out.println("the entered string is a valid integer");}

}

OUTPUT:the entered string is a valid integer

Page 15: Java Progs

4.3 Create a class. Add a default constructer to the class that prints a message “Creating New Object” and the counter. Create an object of this class. And dd an overload constructor to the class that takes a string argument and prints it along with the message and the counter.

SOLUTIONclass objcounter{

public static int c;public objcounter(){

++c;System.out.println("\n creating new object"+cn);

}public objcounter(String ch){

++c;System.out.println(c+ch);

}public static void main(String args[]){

objcounter obj=new objcounter();objcounter obj1=new objcounter("overloaded counter");

}}

Page 16: Java Progs

ASSIGNMENT-55.1Open a file and read it line by line till you find the end of file. If the

data in the line is more than 2 words and 15 characters in total then copy the line to another file else discard the line.

SOLUTION:package ipop;import java.io.*;public class words {

public static void main(String[] args){

int i,words,k;String str="";File f1=new File("C:\\java work\\progs\\src\\ipop\\1");File f2=new File("C:\\java work\\progs\\src\\ipop\\2");

try{FileReader s1=new FileReader(f1);FileWriter s2=new FileWriter(f2);BufferedReader in=new BufferedReader(s1);

while((str=in.readLine())!=null){

k=0;i=0;words=0;

byte [] buffer=str.getBytes();ByteArrayInputStream input=new

ByteArrayInputStream(buffer);while((i=input.read())!=-1){

if(i==32)words++;

k++;}if( words>1 && k>15){

s2.write(str + "\r\n");System.out.println(str);

}

}in.close();s1.close();s2.close();

}

Page 17: Java Progs

catch(Exception e){

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

}

}

Page 18: Java Progs

5.2To print name of the student corresponding to its roll no. The data with cols as roll no and name is provided in the text file.

SOLUTION:import java.io.*;class rollnum{ public static void main(String args[]) {

try {

File f1=new File("file3.txt");FileInputStream fstream = new FileInputStream(f1);BufferedReader br = new BufferedReader(new

InputStreamReader(fstream)); int k;

String strline,strline1;while((strline=br.readLine())!=null){

k=strline.indexOf(" ");strline1=strline.substring(0,k);if(strline1.equals(args[0])){

System.out.println(strline);break;

}}

}catch (Exception e){ System.err.println("Error: " + e.getMessage());

} }}

Page 19: Java Progs

5.3To open a file and delete all occurrences of a string in file provided as I/O from user.

SOLUTION:package ipop;

import java.io.*;public class replace {

/** * @param args */public static void main(String[] args) {

// TODO Auto-generated method stubFile f1=new File("C:\\java work\\progs\\src\\ipop\\1");File f2=new File("C:\\java work\\progs\\src\\ipop\\3");String str="",str1="",key=args[0];try{FileReader fr1=new FileReader(f1);FileWriter fr2=new FileWriter(f2);BufferedReader b1=new BufferedReader(fr1);while((str=b1.readLine())!=null){

str1+=str + "\r\n";

}b1.close();String str2=str1.replaceAll(key,"");fr2.write(str2);fr1.close();fr2.close();}catch(Exception e){

}}

}

Page 20: Java Progs

5.4 To compare two files and printing the lines where they differ.SOLUTION:

import java.io.*;class compare{ public static void main(String args[]) {

try {

File f1=new File("file1.txt"); File f2=new File("file2.txt");

FileInputStream fstream = new FileInputStream(f1); FileInputStream fstream1=new FileInputStream(f2); DataInputStream in = new DataInputStream(fstream);

DataInputStream in1 = new DataInputStream(fstream1); BufferedReader br = new BufferedReader(new InputStreamReader(in));

BufferedReader br1 = new BufferedReader(new InputStreamReader(in1)); String strLine,strline1; while ((strLine = br.readLine()) != null && (strline1=br1.readLine())!=null) {

if(!strLine.equals(strline1)){System.out.println ("file1"+strLine);

System.out.println ("file2"+strline1);}

}if(f1.length()>f2.length()){

while ((strLine = br.readLine()) != null)System.out.println ("file1 "+ strLine);

}else

while ((strline1 = br1.readLine()) != null)System.out.println ("file2 "+strline1);

in.close(); }

catch (Exception e){ System.err.println("Error: " + e.getMessage());

} }}

5.5 Create a frame for taking I/O about a student with two labels, 2 text boxes, radio buttons, list and buttons (AWT).

Page 21: Java Progs

import javax.swing.*;import java.io.*;import java.awt.event.*;public class fees{

JFrame frame=new JFrame("frame1");JLabel name=new JLabel("name");JLabel rollno=new JLabel("rollno");JLabel fees=new JLabel("fees");JTextBox box1=new JTextBox();JTextBox box2=new JTextBox();JTextBox box3=new JTextBox();JPanel panel=new JPanel();public fees(){

frame.setSize(500,500);panel.setLayout(new FlowLayout());frame.add(panel);panel.add(name);panel.add(box1);panel.add(rollno);panel.add(box2);panel.add(class);panel.add(box3);frame.setVisible(true);

}public static void main (string args[]){fees obj=new fees();}}

Page 22: Java Progs

5.6 To print even no. of lines. SOLUTION:import java.io.*;public class evenlines{

public static void main(String args[]){

int i,j=1;File f1=new File("file1.txt");try{

BufferedReader in=new BufferedReader(new InputStreamReader(f1));

while((i=in.readLine())!=null){

if(j%2==0){

System.out.print((char)i);}++j;

}}catch(Exception e){}

}}

Page 23: Java Progs

ASSIGNMENT-6

Q1.WAP to convert numbers in a file to words?

public class digittoword{ public void units(int n) {

switch (n) { case 1: System.out.print("one "); break; case 2: System.out.print("two "); break; case 3: System.out.print("three "); break; case 4: System.out.print("four "); break; case 5: System.out.print("five "); break; case 6: System.out.print("six "); break; case 7: System.out.print("seven "); break; case 8: System.out.print("eight "); break; case 9: System.out.print("nine "); break; } }

public void special(int n) {

switch (n) { case 11: System.out.print(" eleven"); break; case 12: System.out.print(" twelve"); break; case 13:

Page 24: Java Progs

System.out.print(" thirteen"); break; case 14: System.out.print(" fourteen"); break; case 15: System.out.print(" fifteen"); break; case 16: System.out.print(" sixteen"); break; case 17: System.out.print(" seventeen"); break; case 18: System.out.print(" eighteen"); break; case 19: System.out.print(" nineteen"); break; } }

public void tens(int n) {

switch (n) { case 1: System.out.print(" ten "); case 2: System.out.print(" twenty "); break; case 3: System.out.print(" thirty "); break; case 4: System.out.print(" forty "); break; case 5: System.out.print(" fifty "); break; case 6: System.out.print(" sixty "); break; case 7: System.out.print(" seventy "); break; case 8: System.out.print(" eighty "); break;

Page 25: Java Progs

case 9: System.out.print(" ninety "); break; } }

public void hundreds(int n) {

switch (n) { case 1: System.out.print("one hundred "); break; case 2: System.out.print("two hundred "); break; case 3: System.out.print("three hundred "); break; case 4: System.out.print("four hundred "); break; case 5: System.out.print("five hundred "); break; case 6: System.out.print("six hundred "); break; case 7: System.out.print("seven hundred "); break; case 8: System.out.print("eight hundred "); break; case 9: System.out.print("nine hundred "); break; } }

public static void main(String[] args) {

Main obj=new Main(); System.out.println("Enter a number between 0 and 999: "); int number = Integer.parseInt(args[0]); while (number < 0 || number > 999)

{ System.out.println("Input Too Large, "); System.out.print("Enter a number between 0 and 999: ");

Page 26: Java Progs

} if (number > 99 && number < 1000) { int h = number / 100; obj.hundreds(h); int x = 0; x = number % 100; if (x > 10 && x < 20) { obj.special(x); } if (x > 0 && x < 100) {

int tens = x / 10; obj.tens(tens);

int units = x % 10; obj.units(units); } }

if (number > 19 && number < 100) {

int t = number / 10; obj.tens(t);

int u = number % 10; obj.units(u); }

if (number > 10 && number < 20) { obj.special(number); }

if (number < 10) { obj.units(number); } }}

Page 27: Java Progs

Q2:WAP to count numbers of words character & lines in a file?

import java.io.*;public class count{

public static void main(String args[]){

int i,j=0,k=0,m=0;char c;try{File f1=new File("file.txt");FileInputStream in=new FileInputStream(f1);while((i=in.read())!=-1){

System.out.println(i);++j;c=(char)i;if(i==32){

k++;}if(c=='\n'){

k++;m++;

}}--m;--k;}catch(Exception e){}System.out.println("number of characters are" +j);System.out.println("number of words are" + k);System.out.println("number of lines"+ m);

}}

Page 28: Java Progs

Q3:WAP to count number of uppercase lowercase letters & digits in a file?

import java.io.*;public class checkcase{public static void main(String args[]){

int i, l=0,u=0,d=0;

try{

File f1=new File("file.txt");FileInputStream in=new FileInputStream(f1);while((i=in.read())!=-1){

if(i>=65 && i<=90){

++u;}else if(i>=97 && i<=122){

++l;}else if(i>=49 && i<=57){++d;}else{

}}

}catch(Exception e){}System.out.println("uppercase"+u);System.out.println("lowercase"+l);System.out.println("digit"+d);

}}

Page 29: Java Progs

ASSIGNMENT-7:

Q1:Create a frame to enter the name rollno & enter the fees of student in textbox?

import javax.swing.*;import java.io.*;import java.awt.event.*;public class fees{

JFrame frame=new JFrame("frame1");JLabel name=new JLabel("name");JLabel rollno=new JLabel("rollno");JLabel fees=new JLabel("fees");JTextBox box1=new JTextBox();JTextBox box2=new JTextBox();JTextBox box3=new JTextBox();JPanel panel=new JPanel();public fees(){

frame.setSize(500,500);panel.setLayout(new FlowLayout());frame.add(panel);panel.add(name);panel.add(box1);panel.add(rollno);panel.add(box2);panel.add(class);panel.add(box3);frame.setVisible(true);

}public static void main (string args[]){fees obj=new fees();}}

Page 30: Java Progs

Q2:Create a frame to display the use checkboxes,button,textfield?

import javax.swing.*;import java.awt.event.*;import java.io.*;import java.awt.*;public class checkbox implements ActionListener{

JFrame frame1=new JFrame("FRAME1");JPanel panel1=new JPanel();JButton submit=new JButton("SUBMIT");JButton cancle=new JButton("CANCLE");JTextField text1=new JTextField(20);JScrollPane sc=new JScrollPane(area1);JCheckBox c1=new JCheckBox("checkbox1");JCheckBox c2=new JCheckBox("checkbox2");JCheckBox c3=new JCheckBox("checkbox3");JCheckBox c4=new JCheckBox("checkbox4");public checkbox(){

int i;frame1.setSize(500,500);panel1.setLayout(new FlowLayout());frame1.add(panel1);panel1.add(submit);panel1.add(cancle);panel1.add(text1);panel1.add(c1);panel1.add(c2);panel1.add(c3);panel1.add(c4);panel1.add(sc);frame1.setVisible(true);submit.addActionListener(this);cancle.addActionListener(this);

}public void actionPerformed(ActionEvent e){

if(e.getSource()==submit){

c1.setSelected(true);c2.setSelected(true);c3.setSelected(true);c4.setSelected(true);text1.setText("submit");

}if(e.getSource()==cancle){

c1.setSelected(false);

Page 31: Java Progs

c2.setSelected(false);c3.setSelected(false);c4.setSelected(false);text1.setText("cancle");

}}public static void main(String s[]){

checkbox fram1=new checkbox();}

}

Page 32: Java Progs

Q3:create a frame & 256 checkboxes to it?import javax.swing.*;import java.awt.event.*;import java.io.*;import java.awt.*;public class checkbox256{

JFrame frame1=new JFrame("FRAME1");JPanel panel1=new JPanel();public checkbox256(){

int i;frame1.setSize(500,500);panel1.setLayout(new FlowLayout());frame1.add(panel1);for(i=1;i<200;i++){JCheckBox c1=new JCheckBox();panel1.add(c1);}frame1.setVisible(true);

}public static void main(String s[]){

checkbox256 fram1=new checkbox256();}

}

Page 33: Java Progs

ASSIGNMENT-8:

Q1: WAP to Create a text editor.import java.io.*;import javax.swing.*;import java.awt.event.*;import java.awt.*;import java.awt.Toolkit;import java.awt.datatransfer.Clipboard;import java.awt.datatransfer.DataFlavor;import java.awt.datatransfer.StringSelection;import java.awt.datatransfer.Transferable;import java.awt.datatransfer.UnsupportedFlavorException;public class editor implements ActionListener{

public static String str;JFrame frame1=new JFrame(" THAPAR EDITOR");JPanel panel1=new JPanel();JMenu file=new JMenu("FILE");JMenu edit=new JMenu("Edit");JMenuItem fnew=new JMenuItem("New");JMenuItem fopen=new JMenuItem("Open");JMenuItem fsave=new JMenuItem("Save");JMenuItem fsaveas=new JMenuItem("Save As");JMenuItem fexit=new JMenuItem("Exit");JMenuItem cut=new JMenuItem("Cut");JMenuItem copy=new JMenuItem("Copy");JMenuItem paste=new JMenuItem("Paste");JMenuItem mcut=new JMenuItem("Cut");JMenuItem mcopy=new JMenuItem("Copy");JMenuItem mpaste=new JMenuItem("Paste");JMenuBar menubar=new JMenuBar();JEditorPane editorPane = new JEditorPane();JScrollPane editorScrollPane = new JScrollPane(editorPane);JFileChooser fc = new JFileChooser();Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();JPopupMenu pop=new JPopupMenu();public editor(){

editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

editorScrollPane.setPreferredSize(new Dimension(1230, 770));editorScrollPane.setMinimumSize(new Dimension(10, 10));panel1.setLayout(new FlowLayout(0));frame1.add(panel1);frame1.setJMenuBar(menubar);frame1.setSize(1250,790);frame1.setVisible(true);

Page 34: Java Progs

menubar.add(file);menubar.add(edit);file.add(fnew);file.add(fopen);file.add(fsave);file.add(fsaveas);file.add(fexit);edit.add(cut);edit.add(copy);edit.add(paste);pop.add(mcut);pop.add(mcopy);pop.add(mpaste);panel1.add(editorScrollPane);fnew.addActionListener(this);fopen.addActionListener(this);fsave.addActionListener(this);fsaveas.addActionListener(this);fexit.addActionListener(this);copy.addActionListener(this);paste.addActionListener(this);cut.addActionListener(this);mcopy.addActionListener(this);mpaste.addActionListener(this);mcut.addActionListener(this);

frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);editorPane.addMouseListener(new MouseAdapter(){

public void mousePressed(MouseEvent me){

if(me.isPopupTrigger()){

pop.show(me.getComponent(), me.getX(), me.getY());}

}public void mouseReleased(MouseEvent Me){

if(Me.isPopupTrigger()){

pop.show(Me.getComponent(), Me.getX(), Me.getY());}}

});}public void actionPerformed(ActionEvent e){

if(e.getSource()==fnew){

frame1.setVisible(false);editor ed=new editor();

Page 35: Java Progs

}if(e.getSource()==fopen){

int returnVal = fc.showOpenDialog(frame1);if (returnVal == JFileChooser.APPROVE_OPTION){

File file = fc.getSelectedFile();java.net.URL helpURL = editor.class.getResource(file.getName());

try{

editorPane.setPage(helpURL);}catch(Exception f){}

}}if(e.getSource()==fsave){

try{

File f1=fc.getSelectedFile();FileWriter fin=new FileWriter(f1.getName());fin.write(editorPane.getText());fin.close();

}catch(Exception g){}

}if(e.getSource()==fsaveas){

try{

int returnVal = fc.showSaveDialog(frame1);if (returnVal == JFileChooser.APPROVE_OPTION){

File fil = fc.getSelectedFile();FileWriter fin=new FileWriter(fil.getName());fin.write(editorPane.getText());fin.close();

} }catch(Exception f){}

}if(e.getSource()==fexit){

System.exit(0);}if(e.getSource()==copy){

Page 36: Java Progs

Transferable transferableText =new StringSelection(editorPane.getSelectedText());

clipboard.setContents(transferableText,null);}if(e.getSource()==paste){ String grabbed=null;

try{Transferable clipboardContents =clipboard.getContents(null);

if (clipboardContents.isDataFlavorSupported(DataFlavor.stringFlavor)) {

grabbed =(String) clipboardContents.getTransferData(DataFlavor.stringFlavor);}editorPane.replaceSelection(grabbed);}catch(Exception m){}

}if(e.getSource()==cut){

Transferable transferableText =new StringSelection(editorPane.getSelectedText());

clipboard.setContents(transferableText,null);editorPane.replaceSelection(" ");

}if(e.getSource()==mcopy){

Transferable transferableText =new StringSelection(editorPane.getSelectedText());

clipboard.setContents(transferableText,null);}if(e.getSource()==mpaste){ String grabbed=null;

try{Transferable clipboardContents =clipboard.getContents(null);if

(clipboardContents.isDataFlavorSupported(DataFlavor.stringFlavor)) {grabbed =(String)

clipboardContents.getTransferData(DataFlavor.stringFlavor);}

editorPane.replaceSelection(grabbed);}catch(Exception m){}

}if(e.getSource()==mcut){

Transferable transferableText =new StringSelection(editorPane.getSelectedText());

clipboard.setContents(transferableText,null);

Page 37: Java Progs

editorPane.replaceSelection(" ");}

}public static void main (String args[]){

editor ed=new editor();}

}OUTPUT:

Page 38: Java Progs

Q2: WAP to show a bouncing ball on the screen.package javaprogs;import java.applet.*;import java.awt.*;public class Ball extends Applet implements Runnable{

Thread t;int radius;int x,y;public void init(){

x=10;y=590;radius=30;t=new Thread(this);t.start();

}public void paint(Graphics g){

g.drawOval(x,y,radius,radius);g.fillOval(x+6,y+7,radius-25,radius-25);g.fillOval(x+18,y+7,radius-25,radius-25);

g.drawArc(x+11,y+14,radius-20,radius-20,180,180);}public void run(){

try{ for(;;)

{if(y>=580){

int z=y;for(int i=z;i>=10;i-=7){

x+=2;y=i;repaint();t.sleep(40);if(x>=700){

x=0;y=590;break;

}}

}else{

int z=y;

Page 39: Java Progs

for(int i=z;i<=585;i+=7){

x+=2;y=i;repaint();t.sleep(40);if(x>=700){

x=10;y=590;break;

}}

}}

} catch(InterruptedException e) {

System.out.print("Try Again..... Processor's problem"); }

}}

OUTPUT:

Page 40: Java Progs

8.2 WAP TO DESIGN PAINT.

package event1;

import java.awt.*;

import java.awt.event.MouseEvent;

import javax.swing.*;

import java.awt.event.*;

class frmlogin extends JFrame implements MouseMotionListener, MouseListener,ActionListener

{

JButton L1;

JPanel p1;

int x1,y1,x2,y2;

MenuBar mb;

Menu m;

MenuItem i1,i2,i3;

int tool=1;

int rub=0;

public frmlogin()

{

mb=new MenuBar();

m=new Menu("Tools");

i1=new MenuItem("Pencil");

i2=new MenuItem("Line");

i3=new MenuItem("Circle");

m.add(i1);

m.add(i2);

m.add(i3);

i1.addActionListener(this);

i2.addActionListener(this);

Page 41: Java Progs

i3.addActionListener(this);

mb.add(m);

this.setMenuBar(mb);

p1=new JPanel();

p1.setLayout(new GridLayout(1,1));

x1=y1=0;

L1=new JButton("hello");

p1.add(L1);

this.add(p1,BorderLayout.NORTH);

addMouseMotionListener(this);

addMouseListener(this);

this.setSize(400,400);

this.setVisible(true);

}

public void paint(Graphics g)

{

if(tool==1)

g.drawLine(x1,y1,x2,y2);

else if(tool==2)

{

if(rub==1)

g.setColor(Color.blue);

else

g.setColor(Color.black);

g.drawLine(x1, y1, x2, y2);

}

else if(tool==3)

{

if(rub==1)

Page 42: Java Progs

g.setColor(Color.blue);

else

g.setColor(Color.black);

g.drawOval(x2, y2, x1, y1);

}

}

public void mouseMoved(MouseEvent e){}

public void mouseDragged(MouseEvent e)

{

if(tool==1)

pencil(e);

else if(tool==2)

line(e);

else if(tool==3)

circle(e);

}

public void pencil(MouseEvent e)

{

x1=x2;

y1=y2;

L1.setText(" "+e.getX()+","+e.getY());

x2=e.getX();

y2=e.getY();

repaint();

}

public void line(MouseEvent e)

{

rub=1;

repaint();

Page 43: Java Progs

rub=0;

x1=e.getX();

y1=e.getY();

repaint();

}

public void circle(MouseEvent e)

{

rub=1;

repaint();

rub=0;

x1=e.getX();

y1=e.getY();

repaint();

}

public void mouseReleased(MouseEvent e){}

public void mouseClicked(MouseEvent e){}

public void mouseEntered(MouseEvent e){}

public void mouseExited(MouseEvent e){}

public void mousePressed(MouseEvent e)

{

x2=e.getX();

y2=e.getY();

}

public void actionPerformed(ActionEvent e)

{

if(e.getSource()==i1)

tool=1;

else if(e.getSource()==i2)

Page 44: Java Progs

tool=2;

else

tool=3;

}

}

public class event1

{

public static void main(String[] args)

{

new frmlogin();

}

}

OUTPUT:

Page 45: Java Progs

ASSIGNMENT-9:

Q1. To count the no. of upper case and lower case letters in a file

import java.io.*;public class file {

public static void main(String[] args) {File file1 =new File("C:\\java work\\data\\src\\New Text Document.txt");

String str=null;char ch[]=null;int upper=0, lower=0;try{

FileReader fr=new FileReader(file1);BufferedReader br= new BufferedReader(fr);while((str=br.readLine())!=null){

ch=str.toCharArray();for(int i=0; i<str.length(); i++){

if(ch[i]>=97 && ch[i]<=123)lower++;

if(ch[i]>=65 && ch[i]<=91)upper++;

}}fr.close();

}catch(IOException e){

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

System.out.println("Uppercase Count: "+upper+"\nLowercase count: "+lower);}

}

OUTPUT:

Page 46: Java Progs

Q2: To find prime factors of a number entered at console

import java.io.*;public class PrimeFactors {

public static void main(String[] args) {

Integer num=null;int flag=0;try{

System.out.println("Enter a Number");InputStreamReader ins =new InputStreamReader(System.in);BufferedReader br=new BufferedReader(ins); String str=br.readLine(); num=Integer.parseInt(str);

System.out.println("Prime Factors of "+num+" are\n"); for(int i=num/2; i>1; i--) {

if(num%i==0) {

flag++; System.out.println(" "+i);

} } if(flag==0) { System.out.println("No prime factor exists except 1 and number itself"); }}catch(IOException e){

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

}}

OUTPUT:

Page 47: Java Progs

Q3: To delete all occurrences of a string entered by the user import java.io.*;public class DeleteFromFile {

public static void main(String[] args) {

String str=new String("a");String data=null;File file1=null, file2=null;FileReader fr=null;FileWriter fw=null;BufferedReader br=null;try {

data=args[0];}catch(ArrayIndexOutOfBoundsException e){

System.out.println("Provide Input at the Command Line"); }file1=new File("C:\\java work\\data\\src\\New Text

Document.txt ");file2=new File("C:\\java work\\data\\src\\New Text

Document.txt ");try{

fr=new FileReader(file1);br=new BufferedReader(fr);fw=new FileWriter(file2);while((str=br.readLine())!=null){

if(str.indexOf(data)!=-1)fw.write(str.replace(data,""));

elsecontinue;

}fr.close(); br.close();fw.close();System.out.println("Changes made to the File");

}catch(IOException e){

System.out.println("Data not found");}try{

fr=new FileReader(file2);br=new BufferedReader(fr);

Page 48: Java Progs

}catch(FileNotFoundException e){

System.out.println("file not foumd");System.exit(1);

}try{

fw=new FileWriter(file1);while((str=br.readLine())!=null){

fw.write(str);}br.close(); fr.close(); fw.close();

}catch(IOException e){

System.out.println("No input found");System.exit(1);

}}

}

Page 49: Java Progs

Q 4: To demonstrate multiple catch blocks and finally clause

public class MultipleCatch {

public static void main(String[] args) {

try{

int a=args.length;System.out.println("a =" +a);int b=42/a;int c[]={1,2};c[a]=99;System.out.println("b =" +b);System.out.println("c =" +c[0]);

}catch(ArithmeticException e){

System.out.println("Arithmetic Exception");}catch(ArrayIndexOutOfBoundsException e1){

System.out.println("Array index Exception");}finally{

System.out.println("other Exception");}

}}

OUTPUT:

Page 50: Java Progs

Q 5: To count no of characters, words and lines in the file

import java.io.*;public class Count{

public static void main(String args[]){

File file1=null;FileReader fr1=null;BufferedReader br1=null;String str=null;int line_counter=0;int word_counter=0;int char_counter=0;int wc=0;char [] chArray=null;try{

file1= new File("C:\\java work\\data\\src\\New Text Document.txt ");

fr1= new FileReader(file1);br1=new BufferedReader(fr1);while((str=br1.readLine())!=null){

line_counter++;wc=1;chArray=str.toCharArray();int len=str.length();char_counter+=len;for(int i=0; i<len; i++){

if(chArray[i]==' '){

wc++;}

}word_counter+=wc;

}System.out.println("No. of Lines: "+line_counter);System.out.println("No. of Words: "+word_counter);System.out.println("No. of Characters: "+char_counter);br1.close();fr1.close();

}catch(IOException e){

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

}

Page 51: Java Progs

}

OUTPUT:

Page 52: Java Progs

Q 6: To read from a file and display the person's name and phone no without the international code

import java.io.*;public class PhoneBook { public static void main(String[] args) {

File file1=new File("C:\\java work\\data\\src\\New Text Document.txt");FileReader fr= null;BufferedReader br=null;String str=null;char ch[]=null;String name=null;String ph=null;try{

fr=new FileReader(file1);br=new BufferedReader(fr);while((str=br.readLine())!=null){

ch=str.toCharArray();for(int i=0; i<str.length(); i++){

if(ch[i]==' '){

name=str.substring(0,i);ph=str.substring(i+4);

}}System.out.println("Name: "+name+"\nPhone No. :"+ph);

}fr.close();

}catch(IOException e){

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

}

}OUTPUT:

Page 53: Java Progs

Q 7: Read from a file and find out whether the person is male or female

import java.io.*;public class FindGender {public static void main(String[] args) {

File file1=new File("C:\\java work\\data\\src\\New Text Document.txt");FileReader fr =null;BufferedReader br= null;String str=null;char ch[]=null;try{ fr=new FileReader(file1);

br=new BufferedReader(fr);while((str=br.readLine())!=null){ ch=str.toCharArray();

if((ch[0]=='m' || ch[0]=='M') &&(ch[1]=='s' || ch[1]=='S' || ch[2]== 's' || ch[2]=='S') && ( ch[2]=='.' || ch[3]=='.'))

{System.out.println(str+"\tFemale");

}else if((ch[0]=='m' || ch[0]=='M') &&(ch[1]=='r' ||

ch[1]=='R') && (ch[2]!= 's' || ch[2]=='S')&& ( ch[2]=='.'|| ch[3]=='.')){

System.out.println(str+"\tMale");}else{System.out.println(str+"\tNo Suitable Title Found");}

}}

catch(IOException e){

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

}

}OUTPUT:

Page 54: Java Progs

Q 8: To shift the first string from the line of a file to last and the capitalize the first letter of the line while others remain in lower case

import java.io.*;public class ShiftWord{ public static void main(String[] args) {

File file1=new File("C:\\java work\\data\\src\\New Text Document.txt");FileReader fr= null;BufferedReader br=null;String str=null;char ch[]=null;try{

fr= new FileReader(file1);br=new BufferedReader(fr);while((str=br.readLine())!=null){

System.out.println("Original line: "+str+"\n");ch=str.toCharArray();for(int i=0; i<str.length(); i++){

if(ch[i]==' '){

String temp=str.substring(0, i);String temp1=str.substring(i+1);str=temp1+" "+temp;

str=str.substring(0, 1).toUpperCase()+str.substring(1).toLowerCase();System.out.println(str+"\n");break;

}}

}}catch(IOException e){

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

}

}

OUTPUT:

Page 55: Java Progs
Page 56: Java Progs

Q 9: Read from a file and if the number is odd perform a=a/3+1 else a=a/2

import java.io.*;public class FileOperation {

public static void main(String[] args) {

File file1 = new File("C:\\java work\\data\\src\\New Text Document.txt");FileReader fr=null;BufferedReader br= null;String str=null;char ch[]=null;try{

fr=new FileReader(file1);br=new BufferedReader(fr);while((str=br.readLine())!=null){

System.out.println("\nOriginal: "+str+"\n");Integer temp=Integer.parseInt(str);if(temp%2==0){

while(temp!=1){

temp=temp/2;System.out.print(temp+" ");

}}else{

while(temp!=1){

temp=(temp/3)+1;System.out.print(temp+" ");

}

}}fr.close();

}catch(IOException e){

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

}

}OUTPUT:

Page 57: Java Progs
Page 58: Java Progs

Q 10: Read from the file and if string in the file is matched with user string then delete that lineimport java.io.*;public class filecheck {

public static void main(String args[ ]) {

try {

File f1=new File("C:\\java work\\data\\sam");File f2=new File("C:\\java work\\data\\sam1");FileReader fr= new FileReader(f1);FileWriter fw= new FileWriter(f2);BufferedReader br=new BufferedReader(fr);BufferedWriter wr=new BufferedWriter(fw);String str1="",str=br.readLine();InputStreamReader i=new InputStreamReader(System.in); BufferedReader b1=new BufferedReader(i); String st=b1.readLine();//System.out.print(st);while(str!=null){

System.out.println(str);str1+="\n" + str;str=br.readLine();

}str1=str1.replace(st, "");wr.write(str1);System.out.print(str1);wr.close();br.close();

}catch(Exception e){

System.out.print("sorry");}

}}

Page 59: Java Progs

Q 11. Integer to binary conversion. import java.lang.*;import java.io.*;public class DecimalToBinary{

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

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

System.out.println("Enter the decimal value:");String hex = bf.readLine();int i = Integer.parseInt(hex); String by = Integer.toBinaryString(i);System.out.println("Binary: " + by);

}}OUTPUT: