Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Labb7 PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

Exercise-1

a)Write a Java program that prints all real solutions to the quadratic
equation ax2 + bx +c= 0. Read in a, b, c and use the quadratic
formula. If the discriminant b2 -4ac is negative, display a message
stating that there are no real solutions.

import java.util.*;
public class Quadratic
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter any three values:");
int a=s.nextInt();
int b=s.nextInt();
int c=s.nextInt();
int D = b * b - 4 * a * c;
if(D<0)
System.out.println("There is no real solution");
else
System.out.println("There is a real solution");
}
}
Output:
Enter any three values:4 1 1
There is no real solution

Enter any three values:1 2 3


There is no real solution
b)The Fibonacci sequence is defined by the following rule: The first
two values in the sequence are 1 and 1. Every subsequent value is
the sum of the two values preceding it. Write a Java program that
uses both recursive and non recursive functions to print the nth
value in the Fibonacci sequence.
Using Recursion:
import java.util.*;
class RecFibDemo1
{
static int fib(int n)
{
if(n==1 || n==2)
return 1;
else
return (fib(n-1)+fib(n-2));
}
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("enter last number");
int n=s.nextInt();
System.out.println("fibonacci series is as follows");
int res=0;
for(int i=1;i<=n;i++)
{
res=fib(i);
System.out.print(" "+res);
}
System.out.println();
System.out.println(n+"th value of the series is "+res);
}
}
Output:
enter last number
10
fibonacci series is as follows
1 1 2 3 5 8 13 21 34 55
10th value of the series is 55
Without using recursion:
import java.util.Scanner;
class Fact1
{
public static void main(String args[ ])
{
Scanner s=new Scanner(System.in);
int a=1,b=1,c=0;
System.out.println("Enter last value:");
int n=s.nextInt();
System.out.print(a+" "+b);
for(int i=0;i<n-2;i++) {
c=a+b;
a=b;
b=c;
System.out.print(" "+c);
}
System.out.println();
System.out.println(n+"th value of the series is: "+c);
}
}
Output:
Enter last value:
10
1 1 2 3 5 8 13 21 34 55
10th value of the series is: 55
Exercise-2
a)Write a Java program that prompts the user for an integer and
then prints out all prime numbers up to that integer.
import java.util.Scanner;
class PrimeNumbers
{
public static void main(String[] args)
{
int count;
Scanner s=new Scanner(System.in);
System.out.println("Enter a number: ");
int n=s.nextInt();
System.out.println("Prime numbers upto "+n+":");
for(int i=1;i<=n;i++)
{
count=0;
for(int j=1;j<=i;j++)
{
if(i%j==0)
count++;
}
if(count==2)
System.out. print(i+" ");
}
}
}
Output:
Enter a number:
20
Prime numbers upto 20:
2 3 5 7 11 13 17 19
b)Write a java program to multiple two given matrices and find its
transpose.
import java.util.Scanner;
class MatrixMultiplication
{
public static void main(String args[])
{
int m, n, p, q, i, j, k;
Scanner s = new Scanner(System.in);
System.out.println("Enter the number of rows and
columns of First matrix");
m = s.nextInt();
n = s.nextInt();
System.out.println("Enter the number of rows and
columns of Second matrix");
p = s.nextInt();
q = s.nextInt();
if (n != p)
System.out.println("The matrices can't be
multiplied with each other.");
else
{
int a[][] = new int[m][n];
System.out.println("Enter elements of First
matrix");
for(i = 0; i < m; i++)
for (j = 0; j < n; j++)
a[i][j] = s.nextInt();

int b[][] = new int[p][q];


System.out.println("Enter elements of Second
matrix");
for(i = 0; i< p; i++)
{
for (j = 0; j < q; j++)
{
b[i][j] = s.nextInt();
}
}
int c[][] = new int[m][q];
for (i = 0; i < m; i++)
{
for (j = 0; j < q; j++)
{
c[i][j]=0;
for (k = 0; k < p; k++)
{
c[i][j] = c [i][j]+ a[i][k]*b[k][j];
}
}
}
System.out.println("Product of the matrices:");
for (i = 0; i < m; i++)
{
for (j = 0; j < q; j++)
System.out.print(c[i][j]+"\t");
System.out.print("\n");
}
System.out.println("Transpose of the matrices:");
for (i = 0; i < m; i++)
{
for (j = 0; j < q; j++)
System.out.print(c[j][i]+"\t");
System.out.print("\n");
}
}
}
}
Output:
Enter the number of rows and columns of First matrix
22
Enter the number of rows and columns of Second matrix
22
Enter elements of First matrix
10
01
Enter elements of Second matrix
10
01
Product of the matrices:
1 0
0 1
Transpose of the matrices:
1 0
0 1
Exercise-3
a)Java program that checks whether a given string is a palindrome
or not. Ex MALAYALAM is a palindrome.
import java.util.*;
class Palindrome
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the string to check palindrome
or not");
String str1=s.next();
String str2=new StringBuffer(str1).reverse().toString();
if(str1.equals(str2))
System.out.println(str1+" is palindrome");
else
System.out.println(str1+" is not palindrome");
}
}
Output:
Enter the string to check palindrome or not
madam
madam is palindrome
b)Write a Java program for sorting a given list of names in
ascending order.
import java.util.Scanner;
class AlphabeticalOrder
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter number of names you want to
enter:");
int n = s.nextInt();
String names[] = new String[n];
s = new Scanner(System.in);
System.out.println("Enter all the names:");
for(int i = 0; i < n; i++)
{
names[i] = s.nextLine();
}
for(int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j])>0)
{
String temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.println("Names in Sorted Order:");
for(int i = 0; i < n; i++)
{
System.out.print(names[i] + ",");
}

}
}Output:
Enter number of names:4
Enter all the names: randy john roman brock
Names in Sorted Order:brock,john,randy john roman brock,roman
c)Write a Java Program that reads a line of integers, and then
displays each integer, and then sum of all the integers (Use
StringTokenizer class of java.util)

import java.util.*;
class StringTokenizerEx
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("\nEnter A Line Of Integers:");
String line = s.nextLine();

StringTokenizer st = new StringTokenizer(line);


System.out.println("Number of tokens : "+st.countTokens());
int sum = 0;
System.out.println("Tokens are : " );
while (st.hasMoreTokens())
{
int i = Integer.parseInt(st.nextToken());
System.out.println(i);
sum = sum + i;
}
System.out.println("The Sum is :" +sum);
}
}output:
Enter A Line Of Integers:1 2 3 4
Number of tokens : 4
Tokens are :
1
2
3
4
The Sum is :10
Exercise-4
a) Write a Java program that reads a file name from the user, and
then displays information about whether the file exists, whether the
file is readable, whether the file is writable, the type of file and the
length of the file in bytes.
import java.io.*;
class FileProperties
{
public static void main(String[] args)throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter name of the File");
String fname=br.readLine();
File f1=new File(fname);
System.out.println("File Name:"+f1.getName());
System.out.println("Path :"+f1.getPath());
System.out.println("Abs Path :"+f1.getAbsolutePath());
System.out.println(f1.exists()? "Exists":"does not
exists");
System.out.println(f1.canWrite() ? "is writeable" : "is not
writeable");
System.out.println(f1.canRead() ? "is readable" : "is not
readable");
System.out.println(f1.isDirectory() ? "Directory" : "not a
directory");
System.out.println(f1.isFile() ? "is normal file" : "might
be a named pipe");
System.out.println("File Size:"+f1.length()+" Bytes");
}
}
Output:
Enter name of the File
sample.txt
File Name:sample.txt
Path :sample.txt
Abs Path :F:\JavaLab\Exercise-4\sample.txt
Exists
is writeable
is readable
not a directory
is normal file
File Size:26 Bytes
b) Write a Java program that reads a file and displays the file on the
screen, with a line number before each line.
import java.io.*;
class FileDisplay
{
public static void main(String args[]) throws Exception
{
BufferedReader br=new BufferedReader( new
InputStreamReader(System.in));
System.out.println("Enter name of the file");
String fname=br.readLine();
br=new BufferedReader( new FileReader(fname));
String text=br.readLine();;
int line=0;
while(text!=null)
{
line++;
System.out.println(line+" "+text);
text=br.readLine();
}
}
}
Output:
Enter name of the file
sample.txt
1 Hello World.
2 I'm a robot.
c) Write a Java program that displays the number of characters,
lines and words in a text file.
import java.io.*;
import java.util.*;
public class Lines_Words_chars
{
public static void main(String args[]) throws Exception
{
int word = 0,line=0,ch=0;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter name of the file");
String fname=br.readLine();
br=new BufferedReader(new FileReader(fname));
String text=br.readLine();
while(text!=null)
{
StringTokenizer st=new StringTokenizer(text);
word=word+st.countTokens();
line++;
ch=ch+text.length();
text=br.readLine();
}
System.out.println("No. of Lines: "+line);
System.out.println("No. of Words: "+word);
System.out.println("No. of characters: "+ch);
}
}
Output:
Enter name of the file
sample.txt
No. of Lines: 2
No. of Words: 5
No. of characters: 24
Exercise-5
Create an inheritance hierarchy of Rodent, Mouse, Gerbil, Hamster
etc. In the base class provide methods that are common to all
Rodents and override these in the derived classes to perform
different behaviors, depending on the specific type of Rodent.
Create an array of Rodent, fill it with different specific types of
Rodents and call your base class methods.
class Rodent
{
void place()
{
System.out.println("Rodent lives in all countries");
}

void eat()
{
System.out.println("Rodent is eating grass");
}
void tail()
{
System.out.println("Rodent has long tail");
}
}
class Mouse extends Rodent
{
void place()
{
System.out.println("mouse lives in all countries");
}

void eat()
{
System.out.println("mouse is eating plants and meat");
}
void tail()
{
System.out.println("mouse has long tail\n");
}
}
class Gerbil extends Rodent
{
void place()
{
System.out.println("gerbil lives in sandy planes");
}

void eat()
{
System.out.println("gerbil is eating nuts");
}
void tail()
{
System.out.println("gerbil has normal tail\n");
}
}
class Hamster extends Rodent
{
void place()
{
System.out.println("Hamster lives in dry areas");
}

void eat()
{
System.out.println("Hamster is eating seeds");
}
void tail()
{
System.out.println("Hamster is short tail\n");
}
}
class RodentsDemo
{
public static void main(String args[])
{
Rodent r[] = new Rodent[3];
r[0] = new Mouse();
r[1] = new Gerbil();
r[2] = new Hamster();
for(int i=0;i<3;i++)
{
r[i].place();
r[i].eat();
r[i].tail();
}
}
}
Output:
mouse lives in all countries
mouse is eating plants and meat
mouse has long tail

gerbil lives in sandy planes


gerbil is eating nuts
gerbil has normal tail

Hamster lives in dry areas


Hamster is eating seeds
Hamster is short tail
Exercise 6
a) Write a java program to create an abstract class named Shape
that contains an empty method named numberOfSides ( ).Provide
three classes named Trapezoid, Triangle and Hexagon such that
each one of the classes extends the class Shape. Each one of the
classes contains only the method numberOfSides ( ) that shows the
number of sides in the given geometrical figures.
abstract class Shape
{
abstract void numberOfSides();
}
class Trapezoid extends Shape
{
void numberOfSides()
{
System.out.println("No.of Sides of Trapezoid is:"+4);
}
}
class Triangle extends Shape
{
void numberOfSides()
{
System.out.println("No.of Sides of Triangle is:"+3);
}
}
class Hexagon extends Shape
{
void numberOfSides()
{
System.out.println("No.of Sides of Hexagon is:"+6);
}
}
class Sides
{
public static void main(String[] args)
{
Shape s;
s=new Trapezoid();
s.numberOfSides();
s=new Triangle();
s.numberOfSides();
s=new Hexagon();
s.numberOfSides();
}
}
Output:
No.of Sides of Trapezoid is:4
No.of Sides of Triangle is:3
No.of Sides of Hexagon is:6
b) Write a Java program that demonstrates Packages
import IT.*;
public class PackageDemo
{
public static void main(String[] args)
{
Addition a=new Addition(10,20);
a.sum();
Subraction s=new Subraction(30,20);
s.difference();
Multiplication m=new Multiplication(10,20);
m.product();
Division d=new Division(40,20);
d.div();
}
}
package IT;
public class Addition
{
int x,y;
public Addition(int a,int b)
{
x=a;
y=b;
}
public void sum()
{
System.out.println("Sum:"+(x+y));
}
}
package IT;
public class Subraction
{
int x,y;
public Subraction(int a,int b)
{
x=a;
y=b;
}
public void difference()
{
System.out.println("difference:"+(x-y));
}
}
package IT;
public class Multiplication
{
int x,y;
public Multiplication(int a,int b)
{
x=a;
y=b;
}
public void product()
{
System.out.println("product:"+(x*y));
}
}
package IT;
public class Division
{
int x,y;
public Division(int a,int b)
{
x=a;
y=b;
}
public void div()
{
System.out.println("division:"+(x/y));
}
}
Output:
javac -d . Addition.java

javac -d . Subraction.java

javac -d . Multiplication.java

javac -d . Division.java

javac PackageDemo.java

java PackageDemo

Sum:30
difference:10
product:200
division:2
Exercise 7
a) Write a Java program demonstrating the life cycle of a thread.
class ThreadDemo extends Thread
{
public void run()
{
System.out.println(getState());
}
}
class ThreadCycle
{
public static void main(String[] args)
{
ThreadDemo t1=new ThreadDemo();
ThreadDemo t2=new ThreadDemo();
t1.setName("PVPSIT");
t2.setName("VRSEC");
System.out.println(t1.getName()+":"+t1.getState());
System.out.println(t2.getName()+":"+t2.getState());
System.out.println();
t1.start();
System.out.println(t1.getName()+":"+t1.getState());
System.out.println(t2.getName()+":"+t2.getState());
System.out.println();
t2.start();
System.out.println(t1.getName()+":"+t1.getState());
System.out.println(t2.getName()+":"+t2.getState());
}
}
Output:
VPSIT:NEW
VRSEC:NEW
PVPSIT:RUNNABLE
VRSEC:NEW
RUNNABLE
PVPSIT:RUNNABLE
VRSEC:RUNNABLE
RUNNABLE
b) Develop an applet that displays a simple message
import java.awt.*;
import java.applet.*;
/*
<applet code="HelloWorld.class" width=10000 height =1000>
</applet>
*/
public class HelloWorld extends Applet
{
public void paint(Graphics g)
{
g.drawString("PVPSIT",90,90);
}
}
Output:
Exercise 8
a)Develop an applet that receives an integer in one text field, and
computes its factorial Value and returns it in another text field,
when the button named “Compute” is clicked.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Example.class" width=500 height=500>
</applet>
*/
public class Example extends Applet implements ActionListener
{
Label l1,l2;
Button b;
TextField t1,t2;
public void init()
{
l1=new Label("Enter Number");
l2=new Label("Result");
t1=new TextField(10);
t2=new TextField(20);
b=new Button("compute");
add(l1);
add(t1);
add(b);
add(l2);
add(t2);
b.addActionListener(this);

}
public void actionPerformed(ActionEvent ae)
{
int a=Integer.parseInt(t1.getText());
int fact=1;
for(int i=1;i<=a;i++)
fact=fact*i;
t2.setText(""+fact);
}
}
Output:
b)Write a Java program that allows user to draw lines, rectangles
and ovals.
import java.awt.*;
import java.applet.*;
/*
<applet code="GraphicsDemo.class" width=500 height=100>
</applet>

*/
public class GraphicsDemo extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString("welcome",100,100);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.blue);
g.fillOval(220,150,30,30);
g.drawArc(90,150,100,100,0,270);
g.fillArc(270,150,30,30,0,180);
}
}
Output:
Exercise 9
a) Write a Java program that works as a simple calculator. Use a
grid layout to arrange buttons for the digits and for the +, -,*, %
operations. Add a text field to display the result.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Calculator" width=200 height=200>
</applet>
*/

public class Calculator extends Applet implements ActionListener


{
String labels[]={"+","-","*","/","=","C"};
int previous_val=0;
String operator_symbol="";
Button b[]=new Button[16];
TextField t1=new TextField(10);
public void init()
{
setLayout(new BorderLayout());
add(t1,"North");
t1.setText("0");
Panel p=new Panel();
p.setLayout(new GridLayout(4,4));
for(int i=0;i<16;i++)
{
if(i<10)
b[i]=new Button(String.valueOf(i));
else
b[i]=new Button(labels[i%10]);
b[i].setFont(new Font("Arial",Font.BOLD,25));
b[i].addActionListener(this);
p.add(b[i]);
}
add(p,"Center");
}
public void actionPerformed(ActionEvent ae)
{
int res=0;
String button_cap=ae.getActionCommand();
int curr_val=Integer.parseInt(t1.getText());
if(button_cap.equals("C"))
{
t1.setText("0");
previous_val=0;
curr_val=0;
res=0;
operator_symbol="";
}
else if(button_cap.equals("="))
{
res=0;
if(operator_symbol=="+")
res=previous_val+curr_val;
else if(operator_symbol=="-")
res=previous_val-curr_val;
else if(operator_symbol=="*")
res=previous_val*curr_val;
else if(operator_symbol=="/")
res=previous_val/curr_val;
t1.setText(String.valueOf(res));
}
else if(button_cap.equals("+") ||button_cap.equals("-") ||
button_cap.equals("*") || button_cap.equals("/"))
{
previous_val=curr_val;
operator_symbol=button_cap;
t1.setText("0");
}
else
{
int v=curr_val*10+Integer.parseInt(button_cap);
t1.setText(String.valueOf(v));
}
}
}
Output:
b) Write a Java program for handling mouse events.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet implements
MouseListener,MouseMotionListener
{
String msg="";
int mouseX=0, mouseY=0;

public void init()


{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
mouseX=0;
mouseY=10;
msg="Mouse Clicked";
repaint();
}
public void mouseEntered(MouseEvent me)
{
mouseX=0;
mouseY=10;
msg="Mouse Enterd";
repaint();
}
public void mouseExited(MouseEvent me)
{
mouseX=0;
mouseY=10;
msg="Mouse Exited";
repaint();
}
public void mousePressed(MouseEvent me)
{
mouseX=me.getX();
mouseY=me.getY();
msg="Down";
repaint();
}
public void mouseReleased(MouseEvent me)
{
mouseX=me.getX();
mouseY=me.getY();
msg="up";
repaint();
}
public void mouseDragged(MouseEvent me)
{
mouseX=me.getX();
mouseY=me.getY();
msg="*";
showStatus("Dragging mouse at"+mouseX+","+mouseY);
repaint();
}
public void mouseMoved(MouseEvent me)
{
showStatus("Dragging mouse at"+me.getX()+","+me.getY());
}
public void paint(Graphics g)
{
g.drawString(msg,mouseX,mouseY);
}
}
Output:
Exercise 10
a) Write a program that creates a user interface to perform integer
divisions. The user enters two numbers in the textfields, Num1 and
Num2. The division of Num1 and Num2 is displayed in the Result
field when the Divide button is clicked. If Num1 or Num2 were not
an integer, the program would throw a NumberFormatException. If
Num2 were Zero, the program would throw an ArithmeticException
Display the exception in a message dialog box.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="Ex10" width=800 height=200>
</applet>
*/
public class Ex10 extends JApplet implements ActionListener
{
JLabel l1,l2,l3;
JTextField t1,t2,t3;
JButton b1,b2;
public void init()
{
Container cp=getContentPane();
cp.setLayout(new FlowLayout());
l1=new JLabel("Number 1:");
l2=new JLabel("Number 2:");
l3=new JLabel("Number 3:");
t1=new JTextField(6);
t2=new JTextField(6);
t3=new JTextField(6);
b1=new JButton("Divide");
b2=new JButton("Reset");
cp.add(l1); cp.add(t1);
cp.add(l2); cp.add(t2);
cp.add(l3); cp.add(t3);
cp.add(b1); cp.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);

}
public void actionPerformed(ActionEvent ae)
{
int num1=0,num2=0,res=0;
if(ae.getSource()==b1)
{
try
{
num1=Integer.parseInt(t1.getText());
num2=Integer.parseInt(t2.getText());
res=num1/num2;
t3.setText(Integer.toString(res));
}
catch (NumberFormatException nfe)
{

JOptionPane.showMessageDialog(null,"Invalid
Number.Only integers are allowed");

}
catch(ArithmeticException aex)
{

JOptionPane.showMessageDialog(null,"Invalid
Arthmetic Exception Division cannt be are
allowed");
}
}
if(ae.getSource()==b2)
{
t1.setText("");
t2.setText("");
t3.setText("");
}
}
}
Output:
b) Write a Java program that lets users create Pie charts. Design
your own user interface
import java.awt.*;
import java.applet.*;
/*
<applet code="Graphic" width=400 height=400>
</applet>
*/
public class Graphic extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.green);
g.fillArc(110,80,200,200,0,120);
g.drawString("IT Dept:33.3%",10,50);

g.setColor(Color.red);
g.fillArc(110,80,200,200,120,120);
g.drawString("CSE Dept:33.3%",10,80);

g.setColor(Color.blue);
g.fillArc(110,80,200,200,240,120);
g.drawString("ECE Dept:33.3%",10,110);
}

} output:

You might also like