Laboratory Manual: Government Engineering College, Modasa

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

Government Engineering College, Modasa

LABORATORY MANUAL
Information Technology Department

Semester IV

Object Oriented Programming -I


(3140705)

Year 2020-21
NAME: Jethava Deven Sureshbhai
EnrollmentNumber : 190160116030
Government Engineering College, Modasa

This is to certify that Mr. / Mrs. Jethava Deven Sureshbhai

Enrollment No. 190160116030 of Semester IV Computer

Engineering has successfully completed the prescribed

term work/laboratory work of Object Oriented

Programming -I (3140705) course within the four walls

of Government Engineering College, Modasa. This is

required as a partial fulfillment of the said course of

Gujarat Technological University.

Date:

Course In-Charge HOD


Government Engineering College, Modasa

Exp. Page Initial of Course


Title Date Marks
No. No. In-charge
1 Write a Program that displays Welcome to
Java, Learning Java Now and Programming is
fun.
2 Write a program that solves the following
equation and displays the value x and y:
1) 3.4x+50.2y=44.5 2) 2.1x+.55y=5.9 (Assume
Cramer’s rule to solve equation
ax+by=e x=ed-bf/ad-bc
cx+dy=f y=af-ec/ad-bc )
3 Write a program that reads a number in meters,
converts it to feet, and displays the result.
4 Body Mass Index (BMI) is a measure of health
on weight. It can be calculated by taking your
weight in kilograms and dividing by the square
of your height in meters. Write a program that
prompts the user to enter a weight in pounds
and height in inches and displays the BMI.
Note:- 1 pound=.45359237 Kg and 1
inch=.0254 meters.
5 Write a program that prompts the user to enter
three integers and display the integers in
decreasing order.
6 Write a program that prompts the user to enter
a letter and check whether a letter is a vowel or
constant.
7 Assume a vehicle plate number consists of
three uppercase letters followed by four digits.
Write a program to generate a plate number.
8 Write a program that reads an integer and
displays all its smallest factors in increasing
order. For example if input number is 120, the
output should be as follows:2,2,2,3,5.
9 Write a method with following method header.
public static int gcd(int num1, int num2)
Write a program that prompts the user to enter
two integers and compute the gcd of two
integers.
10 Write a test program that prompts the user to
enter ten numbers, invoke a method to reverse
the numbers, display the numbers.
11 Write a program that generate 6*6 two-
dimensional matrix, filled with 0’s and 1’s ,
display the matrix, check every raw and column
have an odd number’s of 1’s.
12 Write a program that creates a Random object
with seed 1000 and displays the first 100
random integers between 1 and 49 using the
NextInt (49) method.
13 Write a program for calculator to accept an
expression as a string in which the operands
and operator are separated by zero or more
spaces.
For ex: 3+4 and 3 + 4 are acceptable
expressions.
14 Write a program that creates an Array List and
adds a Loan object , a Date object , a string, and
a Circle object to the list, and use a loop to
display all elements in the list by invoking the
object’s to String() method.
15 Write the bin2Dec (string binary String)
method to convert a binary string into a decimal
number. Implement the bin2Dec method to
throw a NumberFormatException if the string
is not a binary string.
16 Write a program that prompts the user to enter
a decimal number and displays the number in a
fraction.
Hint: Read the decimal number as a string,
extract the integer part and fractional part from
the string.
17 Write a program that displays a tic-tac-toe
board. A cell may be X, O, or empty. What to
display at each cell is randomly decided. The X
and O are images in the files X.gif and O.gif.
18 Write a program that moves a circle up, down,
left or right using arrow keys.
19 Write a program that displays the color of a
circle as red when the mouse button is pressed
and as blue when the mouse button is released.
20 Write a GUI program that use button to move
the message to the left and right and use the
radio button to change the color for the
message displayed.
21 Write a program to create a file name 123.txt, if
it does not exist. Append a new data to it if it
already exist. Write 150 integers created
randomly into the file using Text I/O. Integers
are separated by space.
22 Write a recursive method that returns the
smallest integer in an array. Write a test
program that prompts the user to enter an
integer and display its product.
23 Write a generic method that returns the
minimum elements in a two dimensional array.
24 Define MYPriorityQueue class that extends
Priority Queue to implement the Cloneable
interface and implement the clone() method to
clone a priority queue.
25 Write a program that reads words from a text
file and displays all the nonduplicate words in
descending order.The text file is passed as a
command-line argument.
Experiment 1
AIM: Write a Program that displays Welcome to Java, Learning Java
Now and Programming is fun.

PROGRAM:

class pra1
{
public static void main(String[] args)
{
System.out.println("Wellcome to java"+","+"Learning java Now"+"
and"+" Programming is fun");
}
}

OUTPUT:
Experiment 2
AIM: Write a program that solves the following equation and
displays the value x and y:
1) 3.4x+50.2y=44.5
2) 2.1x+.55y=5.9
(Assume Cramer’s rule to solve equation
ax+by=e x=ed-bf/ad-bc
cx+dy=f y=af-ec/ad-bc )

PROGRAM:
import java.util.Scanner;
class ready
{
public static void main(String[] args)
{
double a,b,c,d,e,f;
double x,y;
Scanner i=new Scanner(System.in);
System.out.println("enter the value of a=");
a=i.nextDouble();
System.out.println("enter the value of b=");
b=i.nextDouble();
System.out.println("enter the value of c=");
c=i.nextDouble();
System.out.println("enter the value of d=");
d=i.nextDouble();
System.out.println("enter the value of e=");
e=i.nextDouble();
System.out.println("enter the value of f=");
f=i.nextDouble();
x=((e*d)-(b*f))/((a*d)-(b*c));
y=((a*f)-(e*c))/((a*d)-(b*c));

System.out.println("x="+x);
System.out.println("y="+y);
}
}

OUTPUT:
EXPERMENT 3
AIM: Write a program that reads a number in meters,
converts it to feet, and displays the result.

PROGRAM:

import java.util.Scanner;

class prg2

public static void main(String[] args)

double m,f;

Scanner i=new Scanner(System.in);

m=i.nextDouble();

System.out.println("meter="+m);

f=3.28*m;

System.out.println("feet="+f);

}
OUTPUT:
EXPERMENT 4

AIM: Body Mass Index (BMI) is a measure of health on


weight. It can be calculated by taking your weight in
kilograms and dividing by the square of your height in
meters. Write a program that prompts the user to enter a
weight in pounds and height in inches and displays the BMI.
Note:- 1 pound=.45359237 Kg and 1 inch=.0254 meters.

PROGRAM:

import java.util.*;

class prg5

public static void main(String[] args)

double h,w,bmi;

Scanner m=new Scanner(System.in);

System.out.println("hight in inch=");

h=m.nextDouble();

System.out.println("weight in pound=");

w=m.nextDouble();

h=h*0.0254;

System.out.println("hight in meters="+h);
w=w*0.45359237;

System.out.println("weight in kg="+w);

bmi=w/(h*h);

System.out.println("BMI="+bmi);

OUTPUT:
EXPERMENT 5

AIM: Write a program that prompts the user to enter three


integers and display the integers in decreasing order

PROGRAM:

import java.util.*;

class prg3

public static void main(String[] args)

int temp,a,b,c;

Scanner i=new Scanner(System.in);

System.out.println("enter 1'st integer number:");

a=i.nextInt();

System.out.println("enter 2'nd integer number:");

b=i.nextInt();

System.out.println("enter 3'rd integer number:");

c=i.nextInt();

if(a<b)

temp=a;
a=b;

b=temp;

else

if(c>b)

if(c>a)

temp=c;

c=b;

b=a;

a=temp;

else

temp=c;

c=b;

b=temp;

}
}

System.out.println("Decreasing order:" +a+ "\n"+b+"\n"+c);

}
OUTPUT:
EXPERMENT 6

AIM: Write a program that prompts the user to enter a letter


and check whether a letter is a vowel or constant.

PROGRAM:

import java.util.Scanner;

class prg4

public static void main(String[] args)

char ch;

Scanner i=new Scanner(System.in);

System.out.println("add char=");

ch=i.next().charAt(0);

if(ch=='a'||ch=='A'||ch=='e'||ch=='E'||ch=='i'||ch=='I'||ch=='o'||ch=='O'||ch=
='u'||ch=='U')

System.out.println("char is vovel");

else

System.out.println("char is consonants");

}
OUTPUT:
EXPERMENT 7

AIM: Assume a vehicle plate number consists of three


uppercase letters followed by four digits. Write a program to
generate a plate number.

PROGRAM:

public class prg7

public static void main(String[]

args)

int alpha1 = 'A' + (int)

(Math.random() * ('Z' - 'A'));

int alpha2 = 'A' + (int)

(Math.random() * ('Z' - 'A'));

int alpha3 = 'A' + (int)

(Math.random() * ('Z' - 'A'));

int digit1 = (int)(Math.random() *


10);

int digit2 = (int)(Math.random() *

10);

int digit3 = (int)(Math.random() *

10);

int digit4 = (int)(Math.random() *

10);

System.out.println("" + (char)

(alpha1) + ((char)(alpha2)) +

((char)(alpha3)) + digit1 + digit2

+ digit3 + digit4);

}
OUTPUT:
EXPERMENT 8
AIM: Write a program that reads an integer and displays all
its smallest factors in increasing order. For example if input
number is 120, the output should be as follows:2,2,2,3,5.

PROGRAM:

import java.util.Scanner;

public class prg8

public static void main(String[]

args)

int div=2;

Scanner input = new Scanner

(System.in);

System.out.print("Enter Integer

Value : ");

int number = input.nextInt();

while(number > 1)

{
if(number%div==0)

System.out.print(div+",");

number=number/div;

else

div++;

}}
OUTPUT:
EXPERMENT 9

AIM: Write a method with following method header. public


static int gcd(int num1, int num2)
Write a program that prompts the user to enter two integers
and compute the gcd of two integers.

PROGRAM:

import java.util.Scanner;

public class prg9 {

public static void main(String[]

args) {

int num1, num2;

//Reading the input numbers

Scanner scanner = new

Scanner(System.in);

System.out.print("Enter first

number:");
num1 = (int)scanner.nextInt

();

System.out.print("Enter

second number:");

num2 = (int)scanner.nextInt

();

//closing the scanner to

avoid memory leaks

scanner.close();

while (num1 != num2) {

if(num1 > num2)

num1 = num1 - num2;

else

num2 = num2 - num1;

}
//displaying the result

System.out.printf("GCD of

given numbers is: %d", num2);

OUTPUT:
EXPERMENT 10

AIM: Write a test program that prompts the user to enter ten
numbers, invoke a method to reverse the numbers, display
the numbers.

PROGRAM:

import java.util.Scanner;

public class prg10 {

/** Main method */

public static void main

(String[] args) {

Scanner input = new

Scanner(System.in); // Create a

Scanner

int[] numbers = new

int[10]; // Create an array of

length ten
// Prompt the user to

enter ten numbers

System.out.print

("Enter ten numbers: ");

for (int i = 0; i <

numbers.length; i++)

numbers[i] =

input.nextInt();

// Invoke the method

to reverse the numbers

reverse(numbers);

// Display the

numbers

for (int e: numbers)


{

System.out.print(e + " ");

System.out.println();

/** Method reverse reverses

the array passed in the argument */

public static void reverse

(int[] list) {

int temp;

for (int i = 0, j =

list.length - 1; i < list.length / 2; i++, j--)

temp = list[i];

list[i] = list[j];

list[j] = temp;
}

}
OUTPUT:
EXPERMENT 11
AIM: Write a program that generate 6*6 two-dimensional
matrix, filled with 0’s and 1’s , display the matrix, check every
raw and column have an odd number’s of 1’s.

PROGRAM:

import java.util.Scanner;

public class prg11

public static int[][]

create_fill_matrix()

int [][]matrix = new int[6][6];

for(int i=0;i<6;i++)

for(int j=0;j<6;j++)

matrix[i][j]=(int)((Math.random

()*5)%2);

}
}

return matrix;

public static void displayMatrix(int

[][]matrix)

System.out.print("\nMatrix Values

\n");

for(int i=0;i<6;i++)

for(int j=0;j<6;j++)

System.out.print(matrix[i][j]+ "

");

System.out.println();

}
public static void main(String[]

args)

int my_matrix[][];

int i,j,cnt;

my_matrix=create_fill_matrix();

displayMatrix(my_matrix);

System.out.println("\nRows Having

ODD no of 1s");

for(i=0;i<6;i++)

cnt=0;

for(j=0;j<6;j++)

if(my_matrix[i][j]==1)

cnt++;

}
if(cnt%2!=0)

System.out.println("Row - "+(i

+1)+" have ODD no of 1s");

System.out.println("\nColumns

Having ODD no of 1s");

for(i=0;i<6;i++)

cnt=0;

for(j=0;j<6;j++)

if(my_matrix[j][i]==1)

cnt++;

if(cnt%2!=0)
{

System.out.println("Column -

"+(i+1)+" have ODD no of 1s");

}
}OUTPUT:
EXPERMENT 12

AIM: Write a program that creates a Random object with seed 1000
and displays the first 100 random integers between 1 and 49 using
the NextInt (49) method .

PROGRAM:

import java.util.Random;

public class prg12

public static void main(String[]

args)

Random rand = new Random

(1000);

for (int i = 0; i < 100; i+

+)

System.out.format

("%3d",rand.nextInt(49));
if((i+1)%20==0)

System.out.println();

}
OUTPUT:
EXPERMENT 13

AIM: Write a program for calculator to accept an expression


as a string in which the operands and operator are separated
by zero or more spaces.
For ex: 3+4 and 3 + 4 are acceptable expressions.

PROGRAM:

import java.util.Scanner;

public class prg13

public static void main(String[] args)

Scanner input = new Scanner(System.in);

System.out.print("Enter Equation : ");

String str = input.nextLine();

String a = str.replaceAll(" ","");

if (a.length() < 3) {

System.out.println(

"Minimum 2 Opearator and 1 Opearand

Required");
System.exit(0);

int result = 0;

int i = 0;

while(a.charAt(i)!='+' && a.charAt(i)!='-' &&

a.charAt(i)!='*' && a.charAt(i)!='/')

i++;

switch (a.charAt(i)) {

case '+' :

result = Integer.parseInt(a.substring

(0,i))+Integer.parseInt(a.substring(i+1,a.length

()));

break;
case '-' :

result = Integer.parseInt(a.substring(0,i))-

Integer.parseInt(a.substring(i+1,a.length()));

break;

case '*' :

result = Integer.parseInt(a.substring

(0,i))*Integer.parseInt(a.substring(i+1,a.length

()));

break;

case '/' :

result = Integer.parseInt(a.substring

(0,i))/Integer.parseInt(a.substring(i+1,a.length

()));

break;

System.out.println(a.substring(0,i) + ' ' +


a.charAt(i) + ' ' + a.substring(i+1,a.length())

+ " = " + result);

OUTPUT:
EXPERMENT 14

AIM: Write a program that creates an Array List and adds a


Loan object , a Date object , a string, and a Circle object to
the list, and use a loop to display all elements in the list by
invoking the object’s to String() method.

PROGRAM:

import java.util.ArrayList;

import java.util.Date;

public class prg14

public static void main(String[]

args)

ArrayList<Object> arr_list = new

ArrayList<Object>();

arr_list.add(new Loan(5000.50));

arr_list.add(new Date());

arr_list.add(new String("String
class"));

arr_list.add(new Circle(3.45));

for (int i = 0; i < arr_list.size

(); i++)

System.out.println((arr_list.get

(i)).toString());

class Circle

double radius;

Circle(double r)

this.radius=r;

}
public String toString()

return "Circle with Radius

"+this.radius;

class Loan

double amount;

Loan(double amt)

this.amount=amt;

public String toString()

return "Loan with Amount

"+this.amount;

}
}
OUTPUT:
PRACTICAL-15
Aim: Write the bin2Dec (string binary String) method to
convert a binary string into a decimal number. Implement the
bin2Dec method to throw a NumberFormatException if the
string is not a binary string.
PROGRAM:

import java.util.Scanner;

class Practical_15

public static int bin2Dec(String binaryString)

throws NumberFormatException

int decimal = 0;

int strLength=binaryString.length();

for (int i = 0; i < strLength; i++)

if (binaryString.charAt(i) < '0' ||

binaryString.charAt(i) > '1')

{
throw new NumberFormatException("The Input String is not
Binary");

decimal += (binaryString.charAt(i)-'0') *

Math.pow(2, strLength-1-i);

return decimal;

public static void main(String[] args)

Scanner input = new Scanner(System.in);

System.out.print("Enter Binary Value : ");

String str = input.nextLine();

try

System.out.println("Value = " + bin2Dec(str));

catch(NumberFormatException e)

{
System.out.println(e);

OUTPUT:
PRACTICAL-16
Aim: Write a program that prompts the user to enter a
decimal number and displays the number in a fraction.
Hint: Read the decimal number as a string, extract the integer
part and fractional part from the string.
PROGRAM:
java.util.Scanner;

class Fraction{

private int real;

private int imaginary;

Fraction(int r,int img){

real=r;

imaginary=img;

public long gcm(long a, long b) {

return b == 0 ? a : gcm(b, a % b);

}
public String toString() {

long gcm = gcm(real, imaginary);

return real/gcm+"/"+imaginary/gcm;

public class Practical_16 {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

System.out.print import ("Enter a Decimal Number: ");

String decimal=sc.nextLine();

int indexOfDecimal = decimal.indexOf(".");

int len=decimal.substring(indexOfDecimal).length();

int imag_part=(int) Math.pow(10,len-1);

int real_part=(int)(Double.parseDouble(decimal)*imag_part);

Fraction fr=new Fraction(real_part,imag_part);

System.out.println("The Fraction Number is "+fr);

System.out.print("Enter a Decimal Number: ");

decimal=sc.nextLine();

indexOfDecimal = decimal.indexOf(".");

len=decimal.substring(indexOfDecimal).length();

imag_part=(int) Math.pow(10,len-1);
real_part=(int)(Double.parseDouble(decimal)*imag_part);

fr=new Fraction(real_part,imag_part);

System.out.println("The Fraction Number is "+fr);

OUTPUT:
Practical-17

Write a program that displays a tic-tac-toe board. A cell may be X, O, or empty. What to
display at each cell is randomly decided. The X and O are images in the files X.gif and
O.gif.

program
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;

public class OOP_17 extends Application


{
@Override
public void start(Stage primaryStage)
{

GridPane pane = new GridPane();

for (int i = 0; i < 3; i++)


{
for (int j = 0; j < 3; j++)
{
int n = (int)(Math.random() * 3);
if (n == 0)
pane.add(new ImageView(new Image("image/x.gif")), j, i);
else if (n == 1)
pane.add(new ImageView(new Image("image/o.gif")), j, i);
else
continue;
}
}

Scene scene = new Scene(pane, 120, 130);


primaryStage.setTitle("OOP_17");
primaryStage.setScene(scene);
primaryStage.show();
}
}

output:
Practical-18
Write a program that moves a circle up, down, left or right using arrow keys.

program:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.shape.Circle;
import javafx.scene.layout.Pane;
import javafx.geometry.Insets;
import javafx.stage.Stage;

public class OOP_18 extends Application


{
@Override
public void start(Stage primaryStage) {
Pane pane = new Pane();
pane.setPadding(new Insets(30, 30, 30, 30));
Circle circle = new Circle(30, 30, 30);
pane.getChildren().add(circle);

pane.setOnKeyPressed(e -> {
switch (e.getCode()) {
case UP : circle.setCenterY(circle.getCenterY() >
circle.getRadius() ? circle.getCenterY() - 15 :
circle.getCenterY()); break;
case DOWN : circle.setCenterY(circle.getCenterY() <
pane.getHeight() - circle.getRadius() ?
circle.getCenterY() + 15 : circle.getCenterY());
break;
case LEFT : circle.setCenterX(circle.getCenterX() >
circle.getRadius() ? circle.getCenterX() - 15 :
circle.getCenterX()); break;
case RIGHT : circle.setCenterX(circle.getCenterX() <
pane.getWidth() - circle.getRadius() ?
circle.getCenterX() + 15: circle.getCenterX());
}
});

Scene scene = new Scene(pane, 200, 200);


primaryStage.setTitle("OOP_18");
primaryStage.setScene(scene);
primaryStage.show();
pane.requestFocus();
}
}

output:
Practical-19
Write a program that displays the color of a circle as red when the mouse button is pressed
and as blue when the mouse button is released.

program:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
import javafx.scene.paint.Color;
import javafx.scene.layout.StackPane;

public class CircleColor extends Application {


private CirclePane circlePane = new CirclePane();

public void start(Stage primaryStage) {


Pane pane = new Pane();

circlePane.setOnMousePressed(e -> {
circlePane.paintBlack();
});
circlePane.setOnMouseReleased(e -> {
circlePane.paintWhite();
});

Scene scene = new Scene(pane, 200, 200);


primaryStage.setTitle("CircleColor"); // Set the stage title.
primaryStage.setScene(scene); // Place the scene on the stage.
primaryStage.show();

circlePane.requestFocus();

public static void main(String[] args) {


launch(args);

class CirclePane extends StackPane {


private Circle circle = new Circle(50);
public CirclePane() {
getChildren().add(circle);
circle.setStroke(Color.BLACK);
circle.setFill(Color.WHITE);
}
public void paintBlack() {
circle.setFill(Color.BLACK);
}
public void paintWhite() {
circle.setFill(Color.WHITE);
}
}

output:

Practical-20
Write a GUI program that use button to move the message to the left and right and use the radio
button to change the color for the message displayed.

program:
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.BorderPane;
import javafx.scene.text.Text;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.paint.Color;

public class Exercise_16_01 extends Application {


protected Text text = new Text(50, 50, "Programming is fun");

public void start(Stage primaryStage) {


HBox paneForButtons = new HBox(20);
Button btLeft = new Button("<=");
Button btRight = new Button("=>");
paneForButtons.getChildren().addAll(btLeft, btRight);
paneForButtons.setAlignment(Pos.CENTER);
BorderPane pane = new BorderPane();
pane.setBottom(paneForButtons);

HBox paneForRadioButtons = new HBox(20);


RadioButton rbRed = new RadioButton("Red");
RadioButton rbYellow = new RadioButton("Yellow");
RadioButton rbBlack = new RadioButton("Black");
RadioButton rbOrange = new RadioButton("Orange");
RadioButton rbGreen = new RadioButton("Green");
paneForRadioButtons.getChildren().addAll(rbRed,
rbYellow,
rbBlack, rbOrange, rbGreen);

ToggleGroup group = new ToggleGroup();


rbRed.setToggleGroup(group);
rbYellow.setToggleGroup(group);
rbBlack.setToggleGroup(group);
rbOrange.setToggleGroup(group);
rbGreen.setToggleGroup(group);
Pane paneForText = new Pane();
paneForText.setStyle("-fx-border-color: black");
paneForText.getChildren().add(text);
pane.setCenter(paneForText);
pane.setTop(paneForRadioButtons);

btLeft.setOnAction(e -> text.setX(text.getX() - 10));


btRight.setOnAction(e -> text.setX(text.getX() + 10));

rbRed.setOnAction(e -> {
if (rbRed.isSelected()) {
text.setFill(Color.RED);
}
});

rbYellow.setOnAction(e -> {
if (rbYellow.isSelected()) {
text.setFill(Color.YELLOW);
}
});
rbBlack.setOnAction(e -> {
if (rbBlack.isSelected()) {
text.setFill(Color.BLACK);
}
});

rbOrange.setOnAction(e -> {
if (rbOrange.isSelected()) {
text.setFill(Color.ORANGE);
}
});

rbGreen.setOnAction(e -> {
if (rbGreen.isSelected()) {
text.setFill(Color.GREEN);
}
});

Scene scene = new Scene(pane, 450, 150);


primaryStage.setTitle("Exercise_16_01");
primaryStage.setScene(scene);
primaryStage.show();
}
}

output:
Practical – 21

Aim :- Write a program to create a file name 123.txt, if it does not


exist. Append a new data to it if it already exist. write 150 integers
created randomly into the file using Text I/O. Integers are separated by
space.

Program :-
import java.io.*;
import java.util.Scanner;

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

try (
PrintWriter pw = new PrintWriter(new FileOutputStream(new File("123.txt"),
true));
){
for (int i = 0; i < 150; i++)
{
pw.print((int)(Math.random() * 150) + " ");
}
}
catch (FileNotFoundException fnfe)
{
System.out.println("Cannot create the file.");
fnfe.printStackTrace();
}
}
}
Output :-
Practical – 22

Aim :- Write a recursive method that returns the smallest integer in an


array. Write a test program that prompts the user to enter an integer
and display its product.

Program :-
import java.util.Scanner;

class Practical_22
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int product=1;
System.out.print("Enter five integers: ");
int[] list = new int[5];
for (int i = 0; i < list.length; i++)
{
list[i] = input.nextInt();
product *= list[i];
}
System.out.println("The Product of elements is " + product);
}
}

Output :-
Practical – 23

Aim :- Write a generic method that returns the minimum elements in a


two dimensional array.

Program :-
import java.util.Scanner;

public class Pract23


{
public static void main(String[] args)
{
Integer[][] list = new Integer[10][10];
int value = 0;
for (int i = 0; i < list.length; i++)
{
for (int j = 0; j < list[i].length; j++)
{
list[i][j] = value++;
}
}
System.out.println("Max = " + max(list));
}

public static <E extends Comparable<E>> E max(E[][] list)


{
E max = list[0][0];
for (E[] elements : list)
{
for (E element : elements)
{
if (element.compareTo(max) > 0)
{
max = element;
}
}
}
return max;
}
}

Output :-
Practical – 24

Aim :- Define MYPriorityQueue class that extends Priority Queue to


implement the Cloneable interface and implement the clone() method
to clone a priority queue.

Program :-
import java.util.PriorityQueue;

public class Pract24


{
public static void main(String[] args)
{
MyPriorityQueue<String> queue = new MyPriorityQueue<>();
queue.offer("1");
queue.offer("2");
queue.offer("3");

MyPriorityQueue<String> queue1 = null;


try
{
queue1 = (MyPriorityQueue<String>)(queue.clone());
}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
}
System.out.print(queue1);
}

static class MyPriorityQueue<E> extends PriorityQueue<E> implements Cloneable


{
@Override
public Object clone() throws CloneNotSupportedException
{
MyPriorityQueue<E> clone = new MyPriorityQueue<>();
this.forEach(clone::offer);
return clone;
}

}
}

Output :-
Practical – 25

Aim :- Write a program that reads words from a text file and displays
all the nonduplicate words in descending order.The text file is passed as
a command-line argument.

Program :-
import java.io.*;
import java.util.*;

class Practical_25 {
public static void main(String[] args) {
if(args.length==1){
String fileName = args[0];
TreeSet<String> set = new TreeSet<>();
File file = new File(fileName);
try {
Scanner s = new Scanner(file);
while (s.hasNext()){
set.add(s.next());
}
System.out.println(set);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else{
System.out.println("Please, Pass the File Name as Command Line
Argument");
}
}
}

OUTPUT:

You might also like