Download Java - MIET Engineering College

Document related concepts
no text concepts found
Transcript
M.I.E.T POLYTECHNIC COLLEGE, TRICHY
DEPARTMENT OF COMPUTER ENGINEERING
35245-JAVA PROGRAMMING PRACTICAL
SEMESTER:IV
YEAR:II
M SCHEME
LAB EXERCIES
PARTA-CONSOLE APPLICATIONS
1 Write a Java program to display the count of all commands line arguments and list each in a line
2 Write a program to find out sum of digits of given number
3 Write a program to display multiplication table in row, column format
4 Write a program to
a) To find whether the given number is prime or not
b) To display all prime numbers in a given range of numbers
5 Write a program to create an array of integers and accept a number. Check whether it exits in the
array. Create your own exception with appropriate error message and raise the exception when the
element is not found in the array.
6 Write a program to implement stack using Vector class or Array List
7 Write a program to execute any given windows application and report the exit status of the
application
8 Write a program to get a file name at run time and check for its existence check whether it is a
directory or normal file. If it is a normal file display its size and other attributes of the file.
9 Write a program to copy a file to another file using java.io package Classes.
10 Write a program to get a file at runtime and display the number of lines, words and characters in that
file.
PART-B GUI APPLICATIONS
11 Create a Frame with two labels. At runtime display x and y co-ordinates of mouse pointer in the
Labels.
12 Create a Frame and Checkbox group with five Checkboxes with labels as Red, Green, Blue, Yellow and
White. At run time change the background color of Frame using Checkboxes.
13 Create a Frame with 3 Scrollbars representing the three basic colors RED, GREEN and BLUE. Change
the background color of the Frame using the values of Scrollbars.
APPLETS
14 Create an Applet to calculate Simple and Compound interest by passing parameters through
<PARAM> tags of HTML file.
15 Draw a bar chart for the MARKS scored in 5 subjects by a student using
EXNO: 1
COMMAND LINE ARGUMENTS
AIM:
To Display the count of all commands line arguments and list each in a line.
PROCEDURE:
1. Start the program
2. Declare the variable as count=0
3. Calculate the length of arguments
4. Print the value of length
5. Stop the Execution
PROGRAM:
import java.io.*;
class test1
{
Public static void main (String[] args)
{
int count = 0;
System.out.println ("no of arguments:" +args. Length);
for (String s: args)
{
System.out.println(s);
count++;
}
}
}
OUTPUT:
EXNO: 2
SUM OF DIGITS
AIM:
To find out the sum of digits of given number
PROCEDURE:
1. Start the program
2. Declaration of variables
3. Assign a=0,i=0,sum=0;
4. Calculate the sum of digits
5. Print the value
6. Stop the Execution
PROGRAM:
import java.util.Scanner;
class DigitSum
{
public static void main(String args[])
{
int num,a=0,sum=0;
Scanner scan=new Scanner(System.in);
System.out.println("enter the number:");
num=scan.nextInt();
int i=num;
while(i!=0)
{
a=i%10;
i=i/10;
sum=sum+a;
}
System.out.println("sum of the Digits of "+num+" is:"+sum);
}
}
OUTPUT:
EXNO: 3
MULTIPLICATION TABLE
AIM :
To display the multiplication table in row and column format
PROCEDURE:
1. Start the program
2. Declare the variable name as table size
3. Check the condition using for loop statement
4. Print right most column first
5. And print left most column
6. Execute table in multiplication format
7. Print multiplication table
8. Stop the Execution
PROGRAM:
import java.util.Scanner;
class MulTable
{
public static void main(String args[])
{
int n;
Scanner scan=new Scanner(System.in);
System.out.println("enter the table number:");
n=scan.nextInt();
System.out.println("multiplication table for"+n);
System.out.println("-------------------------");
for(int i=1;i<=10;i++)
{
System.out.format("%2d x %d=%3d\n",i,n,i*n);
}
}
}
OUTPUT:
EXNO: 4A
TO CHECK THE NUMBER IS PRIME OR NOT
AIM:
Write a program to check the number is prime or not
PROCEDURE:
1. Start the program
2. Declare the variables named as num,flag=0
3. Check the condition if(num%i==0)it’s not prime number
4. Else number is prime
5. Print the value
6. Stop the execution
PROGRAM:
import java.util.Scanner;
class PrimeCheck
{
public static void main(String args[])
{
int temp;
boolean isPrime=true;
Scanner scan=new Scanner(System.in);
System.out.println("enter a number to check for prime:");
int num=scan.nextInt();
if(num>1)
{
for(int i=2;i<num;i++)
{
temp=num%i;
if(temp==0)
{
isPrime=false;
break;
}
{
isPrime=true;
}
}
if(isPrime)
System.out.println(num+"is a Prime Number");
else
System.out.println(num+"is not a Prime Number");
}
else
System.out.println(num+" is not a Prime Number");
}
}
OUTPUT:
EXNO: 4B
TO DISPLAY ALL PRIME NUMBERS IN A GIVEN RANGE OF NUMBERS
AIM:
To write a program to display all prime numbers in a given range of numbers.
PROGRAM:
1. Start the program
2. Declare the class name as buffered reader
3. Declare the integer variable named as range
4. Check the condition for(i=2;i<=range++)
5. Display the prime number
6. Stop the execution
PROGRAM:
import java.util.Scanner;
public class PrimeRange
{
public static void main(String args[])
{
int s1,s2,i,j,temp;
boolean isPrime=true;
Scanner s=new Scanner(System.in);
System.out.println("enter the lower limit:");
s1=s.nextInt();
System.out.println("enter the upper limit:");
s2=s.nextInt();
System.out.println("the prime number in between the entered limits are:");
for(i=s1<=1?2:s1;i<=s2;i++)
{
for(j=2;j<i;j++)
{
temp=i%j;
if(temp==0)
{
isPrime=false;
break;
}
else
{
isPrime=true;
}
}
if(isPrime)
{
System.out.println(+i+"");
}
}
}
}
OUTPUT:
EXNO: 5
ARRAYS OF INTEGERS
AIM:
To write a program to create an array of integers and accept a number. Check whether it exits in
the array. Create your own exception with appropriate error message and raise the exception when the
element is not found in the array.
PROCEDURE:
1. Start the program
2. Declare the variable name as mylist
3. Print all the array elements using for loop
4. Execute the program
5. Stop the Execution
PROGRAM:
import java.util.Scanner;
class MyExcep extends Exception
{
MyExcep(int value)
{
System.out.println("The number"+value+"is not found in the array");
}
}
class ArrExcep
{
public static void main(String args[])
{
try
{
int n;
boolean found=false;
int s1[]=new int[5];
Scanner s=new Scanner(System.in);
System.out.println("enter 5 numbers to insert in the array:");
for(int i=0;i<=4;i++)
{
s1[i]=s.nextInt();
}
System.out.println("enter the number to search in the array:");
n=s.nextInt();
int num=n;
for(int j=0;j<=4;j++)
{
if(num==s1[j])
{
found=true;
break;
}
else
found=false;
}
if(found)
System.out.println("the number"+n+"is found in the array");
else
throw new MyExcep(n);
}
catch(MyExcep e)
{
}
}
}
OUTPUT:
EXNO:6
TO IMPLEMENT A STACK USING ARRAYLIST
AIM:
To write a program to implement stack using array list
PROCEDURE
1. Start the program
2. Declare the class named as stack demo
3. Declare the array of integer variable
4. Check the condition if(top<capacity-1)
5. Pushed the element into the stack
6.
Check the condition if (top >= 0)
7. Pop the element from the stack
8. Print the element in the stack
9. Stop the execution
PROGRAM:
import java.util.Vector;
import java.util.Scanner;
public class MyStack
{
Vector myVector;
public MyStack()
{
myVector=new Vector();
}
public void push(Object obj)
{
myVector.add(obj);
}
public Object pop()
{
Object obj=null;
if(myVector.size()>0)
{
obj=myVector.elementAt(myVector.size()-1);
myVector.removeElementAt(myVector.size()-1);
}
else
System.out.println("Stack Underflow");
return obj;
}
public Object peek()
{
Object obj=null;
if(myVector.size()>0)
obj=myVector.elementAt(myVector.size()-1);
else
System.out.println("Stack Underflow");
return obj;
}
public static void main(String args[])
{
MyStack stack=new MyStack();
int ch;
do
{
System.out.println("----menu----");
System.out.println("1.push");
System.out.println("2.pop");
System.out.println("3.exit");
System.out.println("----------");
Scanner scan=new Scanner(System.in);
System.out.print("enter your choice:");
ch=scan.nextInt();
switch(ch)
{
case 1:
System.out.print("enter the item to be pushed:");
int n=scan.nextInt();
stack.push(n);
System.out.println("the top of stack now is..."+stack.peek());
break;
case 2:
stack.pop();
System.out.println("The top of the stack now is...."+stack.peek());
break;
}
}
while(ch<3);
}
}
OUTPUT:
EXNO: 7
PROGRAM TO EXECUTE ANY GIVEN WINDOW APPLICATION IN JAVA
AIM:
To write a program to execute any given windows application and report the exit status of the
application.
PROCEDURE:
1. Start the program
2. Declare the variable named as line
3. Check the condition using while loop statement
4. To execute window application
5. And execute report status on exit application
6. Output will be displayed
7. Stop the execution
PROGRAM:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class AppExec
{
public static void main(String[]args)
{
try
{
System.out.println("Creating Process....");
Process process =
Runtime.getRuntime().exec("notepad.exe") ;
process.waitFor();
System.out.println("Program terminated.....");
}
catch(Exception e)
{
System.out.println("::----------Exception-------------::\n"+e);
}
}
}
EXNO: 8
TO CHECK WHETHER IT IS A FILE OR DIRECTORY
AIM:
To write a program to get a file at run time and check for its existence check whether it is a file
or directory or normal file. It is a normal file display its size and other attributes of the file.
PROCEDURE:
1. Start the program
2. Declare class name as file
3. Check the condition using if (isFile)statement
4. If it true ,file is normal file
5. Else it is not file. It is directory
6. Execute the program
7. Stop the execution
PROGRAM:
import java.io.*;
import java.util.Scanner;
public class CheckFile1
{
public static void main(String[]args)
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the path for file or directory");
String path=s.next();
File file=new File(path);
boolean isFile=file.isFile();
if(isFile)
System.out.println(file.getPath()+"is a file.");
else
System.out.println(file.getPath()+"is not a file.");
boolean isDirectory=file.isDirectory();
if(isDirectory)
System.out.println(file.getPath()+"is a directory.");
else
System.out.println(file.getPath()+"is not a directory.");
}
}
PROGRAM:
EX NO: 9
COPY A FILE TO ANOTHER FILE
AIM:
To write a program to copy a file to another file.
PROCEDURE:
1. Start the program.
2. Create the class named as Copybuffer.
3. Create two files named as input text and output text.
4. Create two object and in for file input stream and out for file output stream.
5. Declare the integer variable.
6. Using in object read the input text file content until(c= =-1).
7. Using the out object copy the input text file content into output text file
8. Close in and out object.
PROGRAM:
import java.io.*;
public class CopyBytes
{
public static void main(String[] args)throws IOException
{
File inputFile=new File("old.txt");
File outputFile=new File("new.txt");
FileInputStream in=new FileInputStream(inputFile);
FileOutputStream out=new FileOutputStream(outputFile);
int c;
while((c=in.read())!=-1)
out.write(c);
in.close();
out.close();
}
}
OUTPUT:
D:\jdk1.5.0_01\bin >javac CopyBytes.java
D:\jdk1.5.0_01\bin >java CopyBytes
EXNO:10
TO DISPLAY THE NO OF LINES,CHARS,WORDS IN A FILE
AIM:
To write a program to get a file at runtime and display the number of lines, words and
characters in that file.
PROCEDURE:
1. Start the program
2. Declare the variable named as word_count,char_count,line_count=0
3. Declare the variable named as s,st
4. To get the value form readLine method
5. Check the condition using while loop
6. Increment the count value
7. Calculate the value of character count, word count
8. Output will be displayed
9. Stop the execution
PROGRAM:
import java.lang.*;
import java.io.*;
import java.util.*;
class wordcount
{
public static void main(String arg[]) throws Exception
{
int char_count=0;
int word_count=0;
int line_count=0;
String s;
StringTokenizer st;
BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter filename : ");
s=buf.readLine();
buf=new BufferedReader(new FileReader(s));
while((s=buf.readLine())!=null)
{
line_count++;
st=new StringTokenizer(s," ,;:.");
while(st.hasMoreTokens())
{
word_count++;
s=st.nextToken();
char_count+=s.length();
}
}
System.out.println("Character Count : "+char_count);
System.out.println("Word Count : "+word_count);
System.out.println("Line Count : "+line_count);
buf.close();
}
}
OUTPUT:
PARTB
EXNO: 11
TO DISPLAY THE XYCOORDINATE VALUES OF MOUSE POINTER
AIM:
To create a frame with two label. At runtime displayed x and y co-ordinates of mouse pointer in
the labels
PROCEDURE:
1. Start the program
2. Import the packages using swing
3. Implements the mousecursorlabel from JFrame
4. Add mouse motion listener using JFrame
5. Set the background color
6. Display the background using drawstring method
7. Stop the execution
PROGRAM:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseMove extends JFrame implements MouseMotionListener
{
public JLabel label;
public static void main(String args[])
{
MouseMove mm=new MouseMove();
mm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
MouseMove()
{
setSize(500,400);
setTitle("Java Swing - JFrame Mouse Hover Get Coordinates");
label=new JLabel("No Mouse Event Captured",JLabel.CENTER);
add(label);
addMouseMotionListener(this);
setVisible(true);
}
public void mouseMoved(MouseEvent e)
{
label.setText("Mouse Cursor Coordinates=>X:"+e.getX()+"|Y:"+e.getY());
}
public void mouseDragged(MouseEvent e)
{
}
}
OUTPUT:
EXNO: 12
TO CHANGE THE BACKGROUND COLOR OF FRAME
AIM:
T create a frame and checkbox group with five checkboxes with labels as
red,green,blue,yellowand white.At runtime change the background color of frame using checkboxes.
PROCEDURE:
1. Start the program
2. Create class name as colordemo extends JFrame from item listener
3. Declare the variable name as r=0,g=0,b=0;
4. Declare the five checkboxes
5. Create a color object and set the color values range from 0 to 255
6. Set the back ground color using setback ground method
7. Stop the execution
PROGRAM:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ColorDemo extends JFrame implements ItemListener
{
int r=0,g=0,b=0;
JCheckBox red,green,blue;
JPanel P = new JPanel();
JPanel cpanel = new JPanel();
Container pane = getContentPane();
ColorDemo(String cd)
{
super(cd);
red = new JCheckBox("red");
red.addItemListener(this);
green = new JCheckBox("green");
green.addItemListener(this);
blue = new JCheckBox("blue");
blue.setSelected(true);
blue.addItemListener(this);
cpanel.add(red);
cpanel.add(green);
cpanel.add(blue);
getContentPane().add(cpanel,"North");
setSize(400,400);
setVisible(true);
getContentPane().add(P);
P.setAlignmentX(JComponent.CENTER_ALIGNMENT);
setVisible(true);
}
public static void main(String[] args)
{
ColorDemo cd = new ColorDemo("Color Check Box");
cd.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void itemStateChanged(ItemEvent ie){
if(ie.getItem() == red)
if(red.isSelected()) r=255; else r=0;
if(ie.getItem() == green)
if(green.isSelected()) g=255; else g=0;
if(ie.getItem() == blue)
if(blue.isSelected()) b=255; else b=0;
P.setBackground(new Color(r,g,b));
}
}
OUTPUT:
EXNO:13
TO CHANGE THE BACKGROUND COLOR OF FRAME USING SCROLLBARS
AIM
To create a frame with 3 scrollbars representing the three basic colors RED, GREEN BLUE.
Change the background color of the frame using the values of scrollbars.
PROCEDURE:
1. Start the program
2. Implements the my scroll from adjustment listener
3. Declaring scr_red,scr_green,scr_blue as scrollbar variables
4. Set the size and location of scrollbar
5. Set the background color values range from 0 to 255
6. Stop the execution
PROGRAM:
import java.awt.*;
import java.awt.event.*;
class MyScroll extends Frame implements AdjustmentListener
{
private Scrollbar scr_red,scr_green,scr_blue;
private int r,g,b;
public MyScroll()
{
setTitle("Scrollbar");
setSize(500,500);
setLocation(100,100);
scr_red=new Scrollbar(Scrollbar.HORIZONTAL,0,45,0,300);
scr_green=new Scrollbar(Scrollbar.HORIZONTAL,0,45,0,300);
scr_blue=new Scrollbar(Scrollbar.HORIZONTAL,0,45,0,300);
scr_red.addAdjustmentListener(this);
scr_green.addAdjustmentListener(this);
scr_blue.addAdjustmentListener(this);
setLayout(null);
scr_red.setBounds(10,50,200,20);
scr_green.setBounds(10,80,200,20);
scr_blue.setBounds(10,110,200,20);
add(scr_red);
add(scr_green);
add(scr_blue);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
public void adjustmentValueChanged(AdjustmentEvent ae)
{
if(ae.getSource()==scr_red)
{
r=scr_red.getValue();
}
else if(ae.getSource()==scr_green)
{
g=scr_green.getValue();
}
else if(ae.getSource()==scr_blue)
{
b=scr_blue.getValue();
}
setBackground(new Color(r,g,b));
}
}
class scroll
{
public static void main(String []args)
{
new MyScroll().setVisible(true);
}
}
OUTPUT:
EXNO: 14
SIMPLE INTEREST AND COMPOUND INTEREST USING APPLET
AIM:
Create an applet to calculate simple and compound interest by passing parameters through
<PARAM> tags of HTML file.
PROCEDURE:
1. Start the program
2. Write an html code in command line using <applet>tag
3. Implement the action listener and item listener from loan compound
4. Declaring variable p,r,n,total,total1,si,ci;
5. Declare a variable for the three horizontal scrollbar
6. Calculate the simple interest and compound interest
7. Execute the program
8. Stop the execution
PROGRAM:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code= InterestCalculater.class width="250" height="200">
<param name="Principal" value="10000">
<param name="rate" value="12">
<param name="years" value="5">
</applet>
*/
public class InterestCalculator extends Applet implements ActionListener
{
Button sibtn=new Button("Simple Interest");
Button cibtn=new Button("Compound Interest");
Label lblPrincipal=new Label("Principal");
Label lblInterest=new Label("Interest rate");
Label lblYears=new Label("numbers of years");
Label lblAmount=new Label("Amount");
TextField textPrincipal=new TextField("0",10);
TextField textInterest=new TextField("0",10);
TextField textYears=new TextField("0",10);
TextField textAmount=new TextField("0",10);
public void init()
{
add(sibtn);
add(cibtn);
add(lblPrincipal);
add(textPrincipal);
add(lblInterest);
add(textInterest);
add(lblYears);
add(textYears);
add(lblAmount);
add(textAmount);
sibtn.addActionListener(this);
cibtn.addActionListener(this);
}
public void actionPerformed(ActionEvent evt)
{
int Principal=Integer.parseInt(getParameter("principal"));
String p=Integer.toString(Principal);
textPrincipal.setText(p);
int Interest=Integer.parseInt(getParameter("rate"));
String r=Integer.toString(Interest);
textInterest.setText(r);
int Years=Integer.parseInt(getParameter("Years"));
String n=Integer.toString(Years);
textYears.setText(n);
double IntRate=(double)Interest/100;
if(evt.getSource()==sibtn)
{
double Amount=Principal+(Principal*IntRate*Years);
String amt=Double.toString(Amount);
textAmount.setText(amt);
repaint();
}
else if(evt.getSource()==cibtn)
{
double Amount= Principal * Math.pow(1+IntRate,Years);
String amt=Double.toString(Amount);
textAmount.setText(amt);
repaint();
}
}
}
OUTPUT:
EXNO:15
BARCHART
AIM:
To Draw a bar chart for the MARKS scored in 5 subjects by a student using graphics object.
PROCEDURE:
1. Start the program.
2. Write a html code in command line using parameter and applet tag.
3. Extending the applet from class Bar chart.
4. Declare the n=0 value [] as integer data type.
5. Declare the label array variable as string data type.
6. Initialize the applet using int () method. Use try block and declare an
array with size.
7. Initialize and get a parameter for an array label [n] and value [n].
8. Create an object for number format exception using catch block.
9. Print () method used to display.
10. Repeat the step 12, 13 until [i<n].
11. Set the color red.
12. Draw the string using draw string() method.
13. Draw and run rectangle using fillrect () method.
14. Stop the execution
PROGRAM:
import java.awt.*;
import java.applet.*;
public class BarChart extends Applet
{
int n=0;
String label[]=new String[5];
int value[]=new int[5];
public void init()
{
try
{
label[0]="Tamil";
label[1]="English";
label[2]="Maths";
label[3]="Science";
label[4]="Social";
value[0]=75;
value[1]=57;
value[2]=92;
value[3]=66;
value[4]=80;
catch(Exception e)
{
}
}
}
public void paint(Graphics g)
{
for(int i=0;i<5;i++)
{
g.setColor(Color.blue);
g.drawString(label[i],5,i*50+30);
g.fillRect(60,i*50+10,value[i],30);
}
}
}
<html>
<head>
<title>hai</title>
</head>
<body
<applet code="BarChart.class" width="300" height="300">
</applet>
</body>
</html>
OUTPUT: