Java Record

You might also like

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

Ex.

No:1 IMPLEMENTATION OF RATIONAL NUMBERS


Date:

AIM:
To develop Rational number class in Java and Use JavaDoc comment for documentation.

ALGORITHM:
STEP 1: Start the program
STEP 2: Get numerator and denominator inputs from the user
STEP 3: If denominator is zero, it throws an exception
STEP 4: Else find the Rational number using gcd.
STEP 5: Print the given number in the rational number format.
STEP 5: Stop the program

PROGRAM:
import java.util.Scanner;
class Rational
{
private int numerator;
private int denominator;
public Rational(int n, int d)
{
numerator = n;
denominator = d;
if (denominator == 0)
{
throw new RuntimeException("Denominator is zero");
}
}
public void findRational()
{
int g = gcd(numerator, denominator);
if (g == 1)
{
System.out.println("No Common Divisor for Numerator and Denominator");
}
else
{
numerator = numerator / g;
denominator = denominator / g;
}
}
private int gcd(int m, int n)
{
int d;
while(m % n != 0)
{
d = m % n;
m = n;
n = d;
}
return n;
}
public void display()
{
System.out.println("The rational number:"+numerator + "/" + denominator);

}
}
public class JavaApplication22
{

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter Numerator : ");
int numerator = scanner.nextInt();
System.out.print("Enter Denominator : ");
int denominator = scanner.nextInt();
Rational rational = new Rational(numerator, denominator);
rational.findRational();
rational.display();

} Aim & Algorithm


Program Coding
Compilation and Debugging
Execution and Results
Viva
Total
EX.NO:02 IMPLEMENTATION OF DATE CLASS
Date:
AIM:
To develop Date class in Java similar to the one available in java.util package.
ALGORITHM:
STEP 1: Start the program
STEP 2: Create a class named Mydate and get the date, month and year from the user
STEP 3: Use setDate member method to check whether the date, month and year is valid.
STEP 4: Check for the year is leap year
STEP 5: If the date is valid,Print the date in the dd-mm-yyyy format
STEP 6: Stop the program
PROGRAM:
importjava.util.*;
classMyDate
{
privateint day;
privateint month;
privateint year;
int[] DaysInMonth = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30,31};
public void setDate(int d, int m, int y)
{
boolean valid = isValid(d, m, y);
if (valid)
{
day = d;
month = m;
year = y;
}
else
{
throw new RuntimeException("Invalid Date Format");
}
}
privatebooleanisValid(int d, int m, int y)
{
setLeapYearDays(y);
if (m < 1 || m > 12)
{
return false;
}
if (d < 1 || d >DaysInMonth[m])
{
return false;
}
else
{
return true;
}
}
private void setLeapYearDays(int y)
{
booleanisLeapYear;
if (y % 400 == 0)
{
isLeapYear = true;
}
else if (y % 100 == 0)
{
isLeapYear = false;
}
else if (y % 4 == 0)
{
isLeapYear = true;
}
else
{
isLeapYear = false;
}
if (isLeapYear)
{
DaysInMonth[2] = 29;
}
else
{
DaysInMonth[2] = 28;
}
}
String dateFormat()
{
return day + "-" + month + "-" + year;
}
}
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the day: ");
int d = in.nextInt();
System.out.print("Enter the month: ");
int m = in.nextInt();
System.out.print("Enter the year: ");
int y = in.nextInt();
MyDate today = new MyDate();
today.setDate(d,m,y);
System.out.println("Input Date : " +today.dateFormat());
}

Aim & Algorithm


Program Coding
Compilation and Debugging
Execution and Results
Viva
Total
EX.NO:03 IMPLEMENTATION OF LISP-LIKE-LIST
Date:
AIM:
To implement Lisp-like list in Java. Write basic operations such as 'car', 'cdr', and 'cons'. If L
is a list [3, 0, 2, 5], L.car() returns 3, while L.cdr() returns [0,2,5].
ALGORITHM:
STEP 1: Create a node of a list having data part and link part.
STEP 2: Create a menu having the following choices : insert, car, cdr, adjoin and display.
STEP 3: Read the choice from the user and call the respective m ethods.
STEP 4: Create another class which implements the same interface to implement the concept of
stack through linked list.
STEP 5: To insert Create an object of node and append to the list.
STEP 6: To Perform CAR, Return the first node data.
STEP 7: To perform CDR, Return all the node (data part) in the list except the first node.
PROGRAM:
import java.util.*;
class Lisp
{
//To perform car() function
public int car(List I)
{
Object ob=I.get(0);
String st=ob.toString();
System.out.println("Using a L.car() function");
return Integer.parseInt(st);
}
public List cdr(List I)
{
Object ob=I.remove(0);
Object obj[]=I.toArray();
System.out.println("Using a L.cdr() function");
List list=Arrays.asList(obj);
return list;
}
}
class Demo
{
public static void main(String[] args)
{
//To add the integer value in the ArrayList
List<Integer> I=new ArrayList<Integer>();
I.add(3);
I.add(0);
I.add(2);
I.add(5);
//To print the Return values of Car(),Cdr() functions
Lisp L=new Lisp();
int val=L.car(I);
System.out.println(val);
List list=L.cdr(I);
System.out.println(list);
}
}

Aim & Algorithm


Program Coding
Compilation and Debugging
Execution and Results
Viva
Total
EX.NO:04 IMPLEMENTATION OF JAVA INTERFACE FOR ADT STACK
Date:

AIM:
To design a Java interface for ADT Stack. Develop two different classes that implement this
interface, one using array and the other using linked-list.

ALGORITHM:
STEP 1: Create an interface which consists of three methods namely PUSH, POP
STEP 2: Create a class which implements the above interface to implement the concept of stack
through Array
STEP 3: Define all the methods of the interface to push any element, to pop the top element and to
display the elements present in the stack.
STEP 4: Create another class which implements the same interface to implement the concept of
stack through linked list.
STEP 5: Repeat STEP 4 for the above said class also.
STEP 6: In the main class, get the choice from the user to choose whether array implementation or
linked list implementation of the stack.
STEP 7: Call the methods appropriately according to the choices made by the user in the previous
step.
STEP 8: Repeat step 6 and step 7 until the user stops execution.

PROGRAM:
import java.io.*;
interface stackoperation
{
public void push(int i);
public void pop();
}
class Astack implements stackoperation
{
int stack[];
int top;
Astack()
{
stack=new int[10];
top=0;
}
public void push(int item)
{
if(top==10)
System.out.println("overflow"+top);
else
{
stack[++top]=item;
System.out.println("item pushed");
System.out.println( "value of top is"+top);
}
}
public void pop()
{
if(top<=0)
System.out.println("underflow");
else
{
stack[top]=top--;
System.out.println("item popped");
}
}
public void display()
{
for(int i=1;i<=top;i++)
{
System.out.println("element:"+stack[i]);
}
}
}
class liststack implements stackoperation
{
node top,q;
int count;
public void push(int i)
{
node n=new node(i);
n.link=top;
top=n;
count++;
}
public void pop()
{
if(top==null)
System.out.println("under flow");
else
{
int p=top.data;
top=top.link;
count--;
System.out.println("popped element:"+p);
}
}
void display()
{
for(q=top;q!=null;q=q.link)
{
System.out.println("the elements are:"+q.data);
}
}
class node
{
int data;
node link;
node(int i)
{
data=i;
link=null;
}
}
}
class Demo
{
public static void main(String args[])throws IOException
{
int ch,x=1,p=0,t=0;
DataInputStream in=new DataInputStream(System.in);
do
{
try
{
System.out.println("----------------------------------");
System.out.println("1.Arraystack 2.liststack 3.exit");
System.out.println("-----------------------------------");
System.out.println("enter ur choice:");
int c=Integer.parseInt(in.readLine());
Astack s=new Astack();
switch(c)
{
case 1:
do
{
if(p==1)
break;
System.out.println("ARRAY STACK");
System.out.println("1.push 2.pop 3.display 4.exit");
System.out.println("enter ur choice:");
ch=Integer.parseInt(in.readLine());
switch(ch)
{
case 1:
System.out.println("enter the value to push:");
int i=Integer.parseInt(in.readLine());
s.push(i);
break;
case 2:
s.pop();
break;
case 3:
System.out.println("the elements are:");
s.display();
break;
case 4:
p=1;
continue;
}
}while(x!=0);
break;
case 2:
liststack l=new liststack();
do
{
if(t==1)
break;
System.out.println("LIST STACK:");
System.out.println("1.push 2.pop 3.display 4.exit");
System.out.println("enter your choice:");
ch=Integer.parseInt(in.readLine());
switch(ch)
{
case 1:
System.out.println("enter the value for push:");
int a=Integer.parseInt(in.readLine());
l.push(a);
break;
case 2:
l.pop();
break;
case 3:
l.display();
break;
case 4:
t=1;
continue;
}
}while(x!=0);
break;
case 3:
System.exit(0);
}
}
catch(IOException e)
{
System.out.println("io error");
}
}while(x!=0);

}
}

Aim & Algorithm


Program Coding
Compilation and Debugging
Execution and Results
Viva
Total
EX.NO:05 IMPLEMENTATION OF POLYMORPHISM
Date:
AIM:
To design a Vehicle class hierarchy in Java. Write a test program to demonstrate
Polymorphism.

ALGORITHM:
STEP 1: Start the program
STEP 2: Create a base class named vehicle with constructor to initialize the value and display
method
STEP 3: Extend two classes namely car and lorry from the base class.
STEP 4: Define the method display under the class car by displaying all the entered values.
STEP 5: Define the method display under the class Lorry by displaying all the entered values..
STEP 6: Create an object reference
STEP 7: Create an object for the derived class and assign the object to the base class reference
STEP 8: stop the program

PROGRAM
class Vehicle
{
String regno;
String brand;
int year;
int price;
Vehicle()
{
}
Vehicle(String reg, String brd, int yr, int pr)
{
regno=reg;
brand=brd;
year=yr;
price=pr;
}
void display()
{
System.out.println("registration no: " + regno);
System.out.println("brand: " + brand);
System.out.println("year: " + year);
System.out.println("price: " + price);
}
}
class Car extends Vehicle
{
int totalseats;
Car(String reg, String brd, int yr, int pr,int seat)
{
super(reg,brd,yr,pr);
totalseats=seat;
}
void display()
{
System.out.println("Car Details");
System.out.println("***********");
super.display();
System.out.println("total no of seats: " +totalseats);
}
}
class Lorry extends Vehicle
{
int MaxLoad;
Lorry(String reg, String brd, int yr, int pr, int max)
{
super(reg,brd,yr,pr);
MaxLoad=max;
}
void display()
{
System.out.println("\nLorry Details");
System.out.println("*************");
super.display();
System.out.println("maxload : " +MaxLoad+"tone");
}
}
class Bike extends Vehicle
{
int cc;
Bike(String reg, String brd, int yr, int pr, int c)
{
super(reg,brd,yr,pr);
cc=c;
}
void display()
{
System.out.println("\nBike Details");
System.out.println("************");
super.display();
System.out.println("cc : " +cc);
}
}
public class Vehicledemo {
public static void main(String[] args) {
// TODO code application logic here
Vehicle veh = new Vehicle();
Car ca=new Car("TN 10 1010","Maruti",2008,500000,5);
Lorry lo=new Lorry("TN 10 1010","Tata",2009,1000000,15);
Bike bi=new Bike("TN 10 1010","Pulsar",2013,80000,180);
veh=ca;
veh.display();
veh=lo;
veh.display();
veh=bi;
veh.display();
}

Aim & Algorithm


Program Coding
Compilation and Debugging
Execution and Results
Viva
Total
EX.NO:06 IMPLEMENTATION OF OBJECT SERILIZATION
Date:
AIM:
To design classes for Currency, Rupee, and Dollar. Write a program that randomly generates
Rupee and Dollar objects and write them into a file using object serialization.
ALGORITHM :
STEP 1: Create a class named currency that implements the serializable interface and also it is
the base class for rupee and dollar classes.
STEP 2: Create an object for ObjectOutputStream to open a file in write mode using
FileOutputStream.
STEP 3: Read the user choice to enter rupee or dollar amount.
STEP 4: Generate random numbers as the value of rupee or dollar.
STEP 5: If choice is rupee then, append "Rs" to the value generated, else if choice is dollar
append "$" to the value generated.
STEP 6: Display the appended String and also write it into the file opened using the
writeObject() method.
STEP 7: Close the file.
STEP 8: Create a class named currency that implements the serializable interface and also it is
the base class for rupee and dollar classes.
STEP 9: Create an object for ObjectInputStream to open the file created in program1 in read
mode using FileInputStream.
STEP 10: If the file does not exist or if it is empty show exceptions.
STEP 11: While the End of file is not reached, do the following...
(i) If the value read is a dollar convert into rupee and print to the user otherwise print the rupee as
such.
STEP 12: End the program.

PROGRAM
import java.io.FileOutputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.*;

class Rupee
{
public Rupee()
{
try
{
Object object=new Object();
object="45";
ObjectOutput out=new ObjectOutputStream(new
FileOutputStream("Rupees.dat"));
out.writeObject(object);
out.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
class Dollar
{
public Dollar()
{
try
{
Object object=new Object(); object="45";
ObjectOutput out=new ObjectOutputStream(new
FileOutputStream("Dollar.dat"));
out.writeObject(object);
out.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public class Currencytest {
public static void main(String[] args) {

new Rupee();
new Dollar();
System.out.println("Select Input Type");
System.out.println("\n1.Dollar\n2.Rupee\n\n");
Scanner input=new Scanner(System.in);
int choice=input.nextInt();
if(choice==1)
{
System.out.println("Enter No of Dollar:");
int noDollar=input.nextInt();
String value="";
String filename="Dollar.dat";
FileInputStream fis=null;
ObjectInputStream in=null;
try
{
fis=new FileInputStream(filename);
in=new ObjectInputStream(fis);
value=(String)in.readObject(); in.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
System.out.println("The Equal Rupee
s:"+noDollar*(Integer.parseInt(value)));
System.out.println();
}
else if(choice==2)
{
System.out.println("Enter Rupee:");
int noRupee=input.nextInt();
System.out.println("The Rupee is:"+noRupee); System.out.println();
}
}
}

& Algorithm
Program Coding
Compilation and Debugging
Execution and Results
Viva
Total
EX.NO:07 IMPLEMENTATION OF SCENTIFIC CALCULATOR USING
Date: EVENT DRIVEN PROGRAMMING

AIM:
To develop a scientific calculator using even-driven programming paradigm of Java.
ALGORITHM:
STEP 1: Create a panel consisting of Buttons for various scientific operations.
STEP 2: Create Button actions.
STEP 3: Place the panel onto a frame.
STEP 4: Associate each Button click with the corresponding actionlistener.
PROGRAM:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
public class Calculator
{
public static void main(String[] args)
{
CalculatorFrame frame = new CalculatorFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class CalculatorFrame extends JFrame
{
public CalculatorFrame()
{
setTitle("Calculator");
CalculatorPanel panel = new
CalculatorPanel(); add(panel);
pack();
}
}
class CalculatorPanel extends JPanel
{
private JButton display;
private JPanel panel;
private double result;
private String lastCommand;
private boolean start;
public CalculatorPanel()
{
setLayout(new BorderLayout());
result = 0;
lastCommand ="=";
start = true;
display = new JButton("0");
display.setEnabled(false);
add(display,
BorderLayout.NORTH);
ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();
panel = new JPanel();
panel.setLayout(new GridLayout(6,5));
addButton("7", insert);
addButton("8", insert);
addButton("9", insert);
addButton("/", command);
addButton("CE", command);
addButton("4", insert);
addButton("5", insert);
addButton("6", insert);
addButton("*", command);
addButton("m+", command);
addButton("1", insert);
addButton("2", insert);
addButton("3", insert);
addButton("-", command);
addButton("m-", command);
addButton("0", insert);
addButton(".", insert);
addButton("+/-",command);
addButton("+", command);
addButton("n!", command);
addButton("pow", command);
addButton("1/x", insert);
addButton("SQRT", insert);
addButton("log", insert);
addButton("%",command);
addButton("sin", insert);
addButton("cos", insert);
addButton("tan",insert);
addButton("x2", insert);
addButton("=", command);
add(panel, BorderLayout.CENTER);
}
private void addButton(String label, ActionListener listener)
{
JButton button = new JButton(label);
button.addActionListener(listener);
panel.add(button);
}
private class InsertAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String input = event.getActionCommand(); if
(start==true)
{
display.setText("");
start = false;
}
if(input.equals("1/x"))
display.setText(""+1/Double.parseDouble(display.getText()));
else if(input.equals("SQRT"))
display.setText(""+Math.sqrt(Double.parseDouble(display.getText())));
else if(input.equals("log"))
display.setText(""+Math.log(Double.parseDouble(display.getText())));
else if(input.equals("x2"))
display.setText(""+Double.parseDouble(display.getText())*Double.parse
Double(display.getText()));
else if(input.equals("sin"))
{
Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0;
display.setText(""+Math.sin(angle));
}
else if(input.equals("cos"))
{
Double angle= Double.parseDouble(display.getText())*2.0*Math.PI/360.0;
display.setText(""+Math.cos(angle));
}
else if(input.equals("tan"))
{
Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0;
display.setText(""+Math.tan(angle));
}
else
display.setText(display.getText() + input);
}
}
private class CommandAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if (start==true)
{
if (command.equals("-"))
{
display.setText(command);
start = false;
}
else
lastCommand = command;
}
else
{
calculate(Double.parseDouble(display.getText()));
lastCommand = command;
start = true;
}
}
}
public void calculate(double x)
{
if (lastCommand.equals("+"))
result += x;
else if (lastCommand.equals("-"))
result -= x;
else if (lastCommand.equals("*"))
result *= x;
else if (lastCommand.equals("/"))
result /= x;
else if (lastCommand.equals("="))
result = x;
else if (lastCommand.equals("CE"))
result = 0.0;
else if (lastCommand.equals("m+"))
result = result;
else if (lastCommand.equals("m-"))
result = 0.0;
else if (lastCommand.equals("pow"))
{
double powval=1.0;
for(double i=0.0;i<x;i++)
powval*=result;
result=powval;
}
display.setText(""+ result);
}
}

Aim & Algorithm


Program Coding
Compilation and Debugging
Execution and Results
Viva
Total

You might also like