Foop
Foop
Practical 1
1. Write a program that displays the area and perimeter of a circle that has a radius of 5.5
using the following formula: perimeter = 2 * radius * pi, area = radius * radius * pi
Code :
class prac1_1{
float r = 5.5f;
double area;
area= 3.14*r*r;
double peremeter;
peremeter = 2*3.14*r;
System.out.println(area);
System.out.println(peremeter);
Output :
94.985
34.54
220280152057
2. Average acceleration is defined as the change of velocity divided by the time taken to
make the change, as shown in the following formula: a = v1 - v0/t Write a program that
prompts the user to enter the starting velocity v0 in meters/ second, the ending velocity v1
in meters/second, and the time span t in seconds, and displays the average acceleration.
Here is a sample run: Enter v0, v1, and t: 5.5 50.9 4.5 The average acceleration is 10.0889
Code :
import java.util.Scanner;
import java.util.*;
double v0,v1,t,a;
v0 = sc.nextDouble();
v1 = sc.nextDouble();
t = sc.nextDouble();
a = (v1 - v0)/t;
System.out.println(“a= ”+a);
Output :
40
10
a=3.5
220280152057
3. Write a program that prompts the user to enter a three-digit integer and determines
whether it is a palindrome number. A number is palindrome if it reads the same from right to
left and from left to right. Here is a sample run of this program: Enter a three-digit integer:
121 121 is a palindrome Enter a three-digit integer: 123 123 is not a palindrome
Code :
import java.util.*;
int sum=0,temp,n,r;
n= sc.nextInt();
temp=n;
while(n>0){
r= n%10;
sum = (sum*10) + r;
n=n/10;
if(temp==sum){
System.out.println("Number is plindrome");
else{
Output :
121
Number is palindrome
220280152057
4. Suppose a right triangle is placed in a plane. The right-angle point is placed at (0, 0), and the
other two points are placed at (200, 0), and (0, 100). Write a program that prompts the user to
enter a point with x- and y-coordinates and determines whether the point is inside the triangle.
Here are the sample runs: Enter a point's x- and y-coordinates: 100.5 25.5 The point is in the
triangle Enter a point's x- and y-coordinates: 100.5 50.5 The point is not in the triangle
Code :
import java.util.*;
class p1_4 {
double x,y,z;
x= sc.nextDouble();
y= sc.nextDouble();
z = x + (2*y) - 200;
System.out.println("Point is in Triangle");
else{
}
Output : Enter X coordinate :
100.5
Enter Y coordinate :
50.5
5. The great circle distance is the distance between two points on the surface of a sphere. Let
(x1, y1) and (x2, y2) be the geographical latitude and longitude of two points. The great circle
distance between the two points can be computed using the following formula: d = radius *
arccos(sin(x1) * sin(x2) + cos(x1) * cos(x2) * cos(y1 - y2)) Write a program that prompts the
user to enter the latitude and longitude of two points on the earth in degrees and displays its
great circle distance. The average earth radius is 6,371.01 km. Note that you need to convert
the degrees into radians using the Math.toRadians method since the Java trigonometric
methods use radians. The latitude and longitude degrees in the formula are for north and west.
Use negative to indicate south and east degrees. Here is a sample run: Enter point 1 (latitude
and longitude) in degrees: 39.55, -116.25 Enter point 2 (latitude and longitude) in degrees:
41.5, 87.37 The distance between the two points is 10691.79183231593 km
Code :
import java.util.*;
class p1_5{
double x1,y1,x2,y2,d,r;
x1 = Math.toRadians(sc.nextDouble());
y1 = Math.toRadians(sc.nextDouble());
= Math.toRadians(sc.nextDouble());
y2 = Math.toRadians(sc.nextDouble());
r=6371.01;
}}
220280152057
100
20.5
-25.3
45.3
Practical Number-2
To learn Arrays and Strings in Java
1. Aim: Assume letters A, E, I, O, and U as the vowels. Write a
program that prompts the user to enter a string and displays
the number of vowels and consonants in the string.
Code :
import java.util.*;
public class prac2_1 {
public static void main(String[] args) { int
vcount = 0, ccount = 0;
System.out.println("Enter the string:");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
for (int i=0;i<str.length(); i++) {
if (str.charAt(i) == 'A' || str.charAt(i) == 'E' || str.charAt(i)
== 'I' || str.charAt(i) == 'O' || str.charAt(i) == 'U'||
str.charAt(i)=='a' || str.charAt(i)=='e' || str.charAt(i)=='i'||
str.charAt(i)=='o'|| str.charAt(i)=='u') {
vcount++;
}
else if ((str.charAt(i) >= 'A' && str.charAt(i) <=
'Z') || (str.charAt(i)>='a' && str.charAt(i)<='z')) {
ccount++;
}
}
System.out.println("The number of vowels in string
are " + vcount);
System.out.println("The number of consonants in
string are " + ccount);
1|Page
}
}
Output:
Enter the string:
HELLO
The number of vowels in string are 2
The number of consonants in string are 3
2|Page
220280152057
Code :
import java.util.*;
public class prac2_2 {
public static void main(String[]
args) { int i;
System.out.println("Enter the 1st string:");
Scanner sc = new Scanner(System.in); String
s1 = sc.nextLine(); System.out.println("Enter
the 2nd string:"); String s2 = sc.nextLine();
System.out.println("The largest common prefix
is"); for(i=0;i<s1.length();i++){
if(s1.charAt(0)!=s2.charAt(0))
{ System.out.println("No largest common
prefix "); System.exit(0);
}
else if(s1.charAt(i)==s2.charAt(i))
{ System.out.print(s1.charAt(i));
}
}
}
}
3|Page
220280152057
Output:
Enter the 1st string:
hello
Enter the 2nd string:
welcome
No largest common prefix
4|Page
220280152057
Code :
import java.util.*;
public class prac2_3 {
public static void main(String[] args)
{ int dcount=0;
System.out.println("Enter the
string:"); Scanner sc = new
Scanner(System.in); String str =
sc.nextLine(); if(str.length()<8){
System.out.println("Password must have at
least 8 characters");
System.exit(0);
}
for(int i=0; i<str.length(); i++){
if (str.charAt(i)>='0' &&
str.charAt(i)<='9'){ dcount++;
}
else if((str.charAt(i)>=33 && str.charAt(i)<=64)||
(str.charAt(i)>=91 && str.charAt(i)<=96)||
(str.charAt(i)>=123 && str.charAt(i)<=127))
{ System.out.println("Password should not
contain
special characters");
5|Page
}
}
if(dcount<2){
System.out.println("Password must have at least 2
digits");
}
}
}
6|Page
220280152057
Code :
import java.util.*;
public class prac2_4 {
public static int[] removeduplicates(int[]
a) { int[] temp = new int[a.length];
int k=0;
for (int i = 0; i <= a.length - 1; i++)
{ boolean isDuplicate = false;
for (int j = i + 1; j <= a.length-1;
j++) { if (a[i] == a[j]) {
isDuplicate =
true; break;
}
}
if (!isDuplicate)
{ temp[k] =
a[i]; k++;
}
}
System.out.println("The array after removing
duplicates is:");
for (int l = 0; l < k ; l++)
{ System.out.println(temp[l])
;
}
return Arrays.copyOf(temp,k);
}
7|Page
220280152057
Output:
Enter the elements of array:
1
2
3
1
5
4
2
23
1
2
The array after removing duplicates is:
3
5
4
23
1
2
8|Page
220280152057
Code :
import java.util.*;
public class prac2_5 {
public static int indexofsmallestelement(int[]
array){ int sindex=0;
int selement=array[0];
Scanner sc= new Scanner(System.in);
for(int i=0; i<array.length; i++){
if(array[i]<selement){
selement=array[i];
sindex=i;
}
}
System.out.println("The index of smallest element
is:"); System.out.println(sindex);
return sindex;
}
public static void main(String[] args) { int[] a =
new int[3]; System.out.println("Enter the
elements of array:"); Scanner sc= new
Scanner(System.in);
for(int i=0; i<a.length; i+
+){ a[i]=sc.nextInt();
}
9|Page
220280152057
indexofsmallestelement(a);
}
}
Output:
Enter the elements of array:
6
4
5
The index of smallest element is:
1
10 | P a g e
220280152057
Practical Number-3
1. Aim: Design a class named Rectangle to represent a rectangle.
The class contains: Two double data fields named width and
height that specify the width and height of the rectangle.
The default values are 1 for both width and height.
A no-arg constructor that creates a default rectangle.
A constructor that creates a rectangle with the specified
width and height.
A method named getArea() that returns the area of
this rectangle.
A method named getPerimeter() that returns the perimeter.
Write a test program that creates two Rectangle objects—one
with width 4 and height 40 and the other with width 3.5 and
height 35.9. Display the width, height, area, and perimeter of
each rectangle in this order.
Java Program:
public class
Rectangle { double
height=1; double
width=1;
Rectangle(){
double height;
double width;
}
Rectangle(double height, double
width){ double h=height;
double w=width;
}
return area;
}
Output:
1.0
1.0
160.0
88.0
1.0
1.0
125.64999999999999
78.8
220280152057
Java Program:
Account() {
System.out.println("Constructor called");
id = 0;
balance = 0.0;
annualInterestRate = 0.0; // stores current interest rate
}
return annualInterestRate;
}
return interest;
}
Output:
Balance: 20500.0
Monthly Interest: 76.875
220280152057
Java Program:
Output:
The percentage change in stock price is:
0.434782608695648
220280152057
Practical Number-4
1. Aim: (The Person, Student, Employee, Faculty, and Staff
classes) Design a class named Person and its two subclasses
named Student and Employee. Make Faculty and Staff
subclasses of Employee. A person has a name, address, phone
number, and email address. A student has a class status
(freshman, sophomore, junior, or senior). Define the status as a
constant. An employee has an office, salary, and date hired. A
faculty member has office hours and a rank. A staff member
has a title. Override the toString method in each class to display
the class name and the person’s name.
Write a test program that creates a Person, Student, Employee,
Faculty, and Staff, and invokes their toString() methods.
Java Program:
import java.util.*;
public class Person {
private String name;
private String address;
private String MobileNo;
private String email;
p.name = "Meet";
220280152057
p.address = "Ahmedabad";
p.MobileNo = "9428041999";
p.email = "[email protected]";
System.out.println("Person name is " + p.name);
System.out.println("Person address is " + p.address);
System.out.println("Person mobile number is " +
p.MobileNo);
System.out.println("Person email id is " +
p.email); System.out.println(p);
System.out.println(e);
p.MobileNo);
System.out.println("Faculty email id is " +
p.email); System.out.println(f);
String sophomore;
220280152057
String junior;
String senior;
Output:
Person name is Meet
Person address is Ahmedabad
Person mobile number is 9428041999
Person email id is [email protected]
Person Method
Person@5acf9800
Student name is Dev
Student address is Navsari
Student mobile number is 7516423592
Student email id is [email protected]
Person Method
Student@36baf30c
Employee name is Divy
Employee address is Mehsana
Employee mobile number is 4568754236
Employee email id is [email protected]
Employee Method
Employee@5ca881b5
Java Program:
Accounts(){
id=0;
balance=0.0;
annualInterestRate=0.0;
}
Output:
Id = 101
Balance = 500000.0
AnnualInterestRate = 2.0 %
Monthly Interest Rate =
0.16666666666666666 Monthly Interest =
833.3333333333333 Balance after withdrawal
= 495000.0 Balance after Deposit = 499000.0
id,amount,balance,deposit,withdraw OverDraft
Limit
This account cannot be overdrawn
220280152057
Java Program:
import java.util.*;
import javax.xml.transform.Source;
public class Persons {
System.out.println(t.addCourse("COA"));
System.out.println(t.addCourse("DS"));
System.out.println(t.removeCourse("DS"));
System.out.println(t.toString("Nikunj Sir", "Ahmedabad"));
}
}
double totalGrade=0.0;
double avgGrade=0.0;
for(int i=0; i<this.grades.size();i++){
totalGrade += this.grades.get(i);
}
avgGrade = (double)
totalGrade/this.grades.size(); return avgGrade;
}
add = true;
}
}
return add;
}
Output:
The name is Meet and the address is Ahmedabad
Dev
Navsari
Student: Dev ( Navsari )
This is Student SubClass
9
9
9
9
220280152057
Practical Number-5
1. Aim: Write a superclass called Shape (as shown in the
class diagram), which contains:
• Two instance variables color (String) and filled (boolean).
• Two constructors: a no-arg (no-argument) constructor
that initializes the color to "green" and filled to t rue, and a
constructor that initializes the color and filled to the given
values.
• Getter and setter for all the instance variables. By
convention, the getter for a boolean variable xxx is called
isXXX() (instead of getXxx() for all the other types).
• A toString() method that returns "A Shape with color of
xxx and filled/Not filled".
Write a test program to test all the methods defined in Shape.
220280152057
Java Program:
class Shape{
protected String color;
protected boolean filled;
Shape(){
this.color = "green";
this.filled = true;
}
Shape(String color,boolean filled){
this.color = color;
220280152057
this.filled = filled;
}
public String color(String color){
return color;
}
public String toString(){
return "A shape with color "+color+" has filled value "+filled;
}
}
class Circle1 extends Shape{
private double rad;
public double getRad() {
return rad;
}
this.rad = rad;
}
Circle1(double rad,String color,boolean
filled){ this.rad = rad;
this.filled = filled;
this.color = color;
}
public double getperimeter1(){
if(rad<0){
System.out.println("invalid
radius"); return -1;
}
else{
double p = 2*Math.PI*rad;
return p;
}
}
public double getArea1(){
if(rad<0){
System.out.println("invalid
radius"); return -1;
}
else{
220280152057
double p = Math.PI*rad*rad;
return p;
}
}
@Override
public String toString() {
return "a circle with radius "+rad+" subclass
of "+ super.toString();
}
}
class Rectangle1 extends Shape {
protected double length;
protected double width;
Rectangle1() {
this.length = 1;
this.width = 1;
}
public void setLength(double
length) { this.length = length;
}
public void setWidth(double
width) { this.width = width;
}
220280152057
super(length,length);
}
Square1(double length,String color,boolean
filled){ super(length,length,color,filled);
}
@Override
public void setLength(double
length) { super.setLength(length);
}
@Override
public double getLength() {
return super.getLength();
}
public double area1(){
if(length < 0){
System.out.println("invalid length. ..... ");
return -1;
}
else{
double area = length*length;
return area;
}
}
220280152057
System.out.println(s.toString());
System.out.println(s1.toString());
System.out.println(c1.toString());
220280152057
System.out.println(c3.toString());
System.out.println(r2.toString());
System.out.println("area of rectangle is\n "+r2.Area1());
System.out.println("perimeter of rectangle
is\n "+r2.perimeter());
Square1 a = new Square1();
System.out.println(a.toString());
System.out.println("area of square with length
"+a.getLength()+" is\n "+a.area1());
System.out.println("perimeter of square with
length "+a.getLength()+" is\n "+a.perimeter());
Square1 a1 = new Square1(2);
System.out.println(a1.toString());
System.out.println("area of square with
length "+a1.getLength()+" is\n "+a1.area1());
System.out.println("perimeter of square with
length "+a1.getLength()+" is\n "+a1.perimeter());
Square1 a2 = new Square1(3,"golden",false);
System.out.println(a2.toString());
Output:
A shape with color green has filled value true
A shape with color pink has filled value false
a circle with radius 1.0 subclass of A shape with color green
has filled value true
area of circle with radius 1.0 is
3.141592653589793
perimeter of circle with radius 1.0 is
6.283185307179586
a circle with radius 2.0 subclass of A shape with color green
has filled value true
area of circle with radius 2.0 is
12.566370614359172 perimeter
of circle with radius 2.0 is
12.566370614359172
a circle with radius 3.0 subclass of A shape with color blue
has filled value true
area of circle with radius 3.0 is
28.274333882308138 perimeter
of circle with radius 3.0 is
18.84955592153876
rectangle length 1.0 and width 1.0 subclass of A shape
with color green has filled value true
area of rectangle is
220280152057
1.0
perimeter of rectangle is
4.0
rectangle length 3.0 and width 2.0 subclass of A shape
with color green has filled value true
area of rectangle is
6.0
perimeter of rectangle is
10.0
rectangle length 4.0 and width 2.0 subclass of A shape
with color silver has filled value true
area of rectangle is
8.0
perimeter of rectangle is
12.0
square length 1.0 and width 1.0 subclass of ractangle length 1.0 and
width 1.0 subclass of A shape with color green has filled value true
area of square with length 1.0 is
1.0
perimeter of square with length 1.0 is
4.0
square length 2.0 and width 2.0 subclass of rectangle length 2.0 and
width 2.0 subclass of A shape with color green has filled value true
area of square with length 2.0 is
4.0
220280152057
Java Program:
else{
double area = (double)
(length*width); return area;
}
}
}
class Triangle4 extends Shape3{
protected int base;
protected int height;
Triangle4(int base,int height){
this.base = base;
this.height = height;
}
public int getBase() {
return base;
}
public int getHeight() {
return height;
}
@Override
public double getArea() {
if(height < 0 && base < 0){
System.out.println("invalid base and
height ... "); return -1;
}
else{
double area = (double)
(0.5*height*base); return area;
}
}
}
public class prac5_2 {
public static void main(String[] args) {
220280152057
Output:
length of the rectangle is 2 and width is 3
color of the shape is red and area is 6.0
base of the triangle is 2 and height is 4
color of the shape is red and area is 4.0
220280152057
Java Program:
interface Comparable{
public void toComparable(ComparableCircle o);
}
/ Circle 1 class is consider from practical (i) of
5 class ComparableCircle extends Circle1
implements Comparable{
ComparableCircle(double
rad){ super(rad);
}
public void toComparable(ComparableCircle
o){ if(getArea1() < 0 || o.getArea1() < 0)
{ System.out.println("error: invalid. ... ");
}
else
{ if(getArea1()>o.getArea1()
){
System.out.println("1st circle has greater
area"); } else if (getArea1() == o.getArea1()) {
System.out.println("both circle has same area");
}
else{
System.out.println("2nd circle has greater area");
}
}
}
}
220280152057
Output:
2nd circle has greater area
220280152057
Practical Number-6
1. Aim: Write a program that meets the following requirements: ■
Creates an array with 100 randomly chosen integers.
■ Prompts the user to enter the index of the array, then displays
the corresponding element value. If the specified index is out of
bounds, display the message Out of Bounds.
(ArrayIndexOutOfBoundsException)
Java Program:
import java.util.*;
public class prac6_1 {
public static void main(String[] args)
{ Scanner sc = new
Scanner(System.in); int a[] = new
int[100];
Random r = new Random();
for(int i=0; i<100; i++){
a[i]=r.nextInt();
}
System.out.println("Enter the index:");
int i = sc.nextInt();
try{
System.out.println("The element of that index is "+ a[i]);
}
catch(Exception e){
e.printStackTrace();
}
System.out.println("Program Executed
Successfully"); sc.close();
}
}
220280152057
Output:
Enter the index:
5
The element of that index is 2004793661
Program Executed Successfully
Java Program:
import java.util.*;
public class prac6_2 {
public static void main(String[] args)
{ Scanner sc = new
Scanner(System.in); int a, b;
try{
System.out.println("Enter two
numbers:"); a = sc.nextInt();
b = sc.nextInt();
System.out.println("The addition is "+ (a + b));
}
catch(InputMismatchException
e){ e.printStackTrace();
}
System.out.println("Program Executed
Successfully"); sc.close();
}
}
220280152057
Output:
Enter two numbers:
5
6
The addition is 11
Program Executed Successfully
Java Program:
if(a<side2){
a = side2;
if(a<side3){
a = side3;
}
}
if(a == side1)
if(a >= side2+side3) throw new
IllegalTriangleException(); if(a == side2)
if(a >= side1+side3) throw new
IllegalTriangleException(); if(a == side3)
if(a >= side2+side1) throw new IllegalTriangleException();
this.side1 =side1;
this.side2 =side2;
this.side3 =side3;
}
}
public class prac6_3 {
public static void main(String[]
args) { try{
Triangle a = new Triangle(1,2,11); System.out.println("It
is a triangle as it follows the rule");
}
catch(Exception e){
System.out.println("Not a Triangle as it does not
follow the rule");
e.printStackTrace();
}
System.out.println("Program Executed Successfully");
}
}
220280152057
Output:
Not a Triangle as it does not follow the rule
IllegalTriangleException: one side is grater than other two side
at Triangle.<init>(prac6_3.java:30)
at prac6_3.main(prac6_3.java:40)
Program Executed Successfully
220280152057
Practical Number-7
1. Aim: (Extend Thread) Write a program to create a
thread extending Thread class and demonstrate the use
of slip() method.
Java Program:
System.out.println(Thread.currentThread().getName() +
" is awake");
}
}
Output:
main is start
main is end
A new thread is formed Thread-1
A new thread is formed Thread-0
A new thread is formed Thread-3
A new thread is formed Thread-6
A new thread is formed Thread-7
A new thread is formed Thread-5
A new thread is formed Thread-4
puttingThread-3 in sleep
puttingThread-4 in sleep
A new thread is formed Thread-
9 puttingThread-9 in sleep
A new thread is formed Thread-2
A new thread is formed Thread-8
puttingThread-6 in sleep
puttingThread-1 in sleep
puttingThread-0 in sleep
puttingThread-5 in sleep
puttingThread-7 in sleep
puttingThread-2 in sleep
puttingThread-8 in sleep
Thread-9 is awake
Thread-6 is awake
Thread-1 is awake
220280152057
Thread-0 is awake
Thread-5 is awake
Thread-7 is awake
Thread-2 is awake
Thread-8 is awake
Thread-3 is awake
Thread-4 is awake
220280152057
Java Program:
System.out.println(Thread.currentThread().getName()
+ " is end");
220280152057
}
public void run()
{
System.out.println("A new thread is formed "
+ Thread.currentThread().getName());
System.out.println("putting" +
Thread.currentThread().getName() + " in sleep");
try{
Thread.sleep(2000);
}catch(Exception e)
{}
System.out.println(Thread.currentThread().getName() +
" is awake");
}
}
Output:
main is start
A new thread is formed Thread-0
puttingThread-0 in sleep
Thread-0 is awake
Thread-2 is awake
main is end
220280152057
Java Program:
import java.lang.*;
{
System.out.println("adding 1 in sum by the "
+ Thread.currentThread().getName());
prac7_3.sum++;
System.out.println("now value of sum is :");
System.out.println(sum.intValue());
System.out.println("");
}
}
}
Output:
value of sum is 0
Practical Number-8
1. Aim: (Remove text) Write a program that removes all the
occurrences of a specified string from a text file. For
example, invoking java Practical7_1 John filename removes
the string John from the specified file. Your program should
get the arguments from the command line.
Java Program:
import java.io.*;
import java.util.*;
String s1 = input.nextLine();
s2.add(removeString(args[0], s1));
}
}
try (
// Create output file
PrintWriter output = new PrintWriter(file);)
{ for (int i = 0; i < s2.size(); i++) {
output.println(s2.get(i));
}
}
}
Output:
Usage: java RemoveText filename
220280152057
Java Program:
import java.io.*;
import java.util.*;
characters += line.length();
}
}
try (
// Create input file
Scanner input = new Scanner(file);)
{ while (input.hasNext()) {
String line = input.next();
words++;
}
}
// Display results
System.out.println("File " + file.getName() + "
has"); System.out.println(characters + "
characters"); System.out.println(words + "
words"); System.out.println(lines + " lines");
}
}
Output:
Usage: java filename
220280152057
Java Program:
import java.util.*;
import java.io.*;
Output:
[4, 6, 11, 17, 24, 27, 29, 57, 66, 67, 70, 71, 72, 72, 74, 84,
93,
110, 114, 115, 119, 120, 129, 135, 136, 152, 162, 164, 169, 172,
172, 176, 180, 187, 203, 203, 207, 209, 212, 222, 223, 227, 238,
239, 241, 243, 243, 244, 251, 261, 267, 270, 274, 276, 281, 282,
284, 286, 290, 294, 295, 295, 296, 301, 311, 312, 313, 314, 321,
327, 329, 329, 342, 343, 349, 349, 350, 365, 369, 378, 389, 397,
404, 406, 409, 416, 418, 425, 440, 443, 445, 450, 461, 464, 466,
476, 483, 491, 494, 497]
220280152057
Practical Number-9
1. Aim: (Decimal to binary) Write a recursive method that
converts a decimal number into a binary number as a string. The
method header is: public static String dec2Bin(int value). Write
a test program that prompts the user to enter a decimal number
and displays its binary equivalent.
Java Program:
}
public static void main(String[] args) { System.out.println("The
equivalent binary of given number
is "+dec2Bin(15));
}
}
Output:
The equivalent binary of given number is 1111
220280152057
Java Program:
import java.util.*;
class E implements Comparable<E>
{
int i;
E(int a)
{
this.i = a;
}
public int compareTo(E e)
{
if(e.i == this.i) return
0; if(e.i < this.i) return
1; else return -1;
}
}
public class prac9_2 {
public static ArrayList<E> removeDuplicates(ArrayList<E>
list) { ArrayList <E> newa = new ArrayList<E>();
}
newa.add(list.get(list.size()-1));
return newa;
}
public static void main(String[] args) {
Random r = new Random();
ArrayList <E> arrx = new
ArrayList<E>(); E[] a = new E[10];
for(int i = 0 ; i < 5 ; i = i+2)
{ int b = r.nextInt();
a[i] = new E(b);
a[i+1] = new E(b);
arrx.add(a[i]);
arrx.add(a[i+1]);
}
Output:
Initial the element of arraylist are
-1740604387 -1740604387 -2005072672 -2005072672
750077308 750077308
Java Program:
int low = 0;
int high = list.length - 1;
if (list[mid].compareTo(value) < 0)
low = mid + 1;
else
220280152057
high = mid - 1;
}
return -1;
}
}
Output:
The element 9 is present at index: 9
The element 5 is present at index: 5
220280152057
Practical Number-10
1. Aim: (Store numbers in a linked list) Write a program that
lets the user enter numbers from a graphical user interface
and displays them in a text area, as shown in Figure. Use a
linked list to store the numbers. Do not store duplicate
numbers. Add the buttons Sort, Shuffle, and Reverse to sort,
shuffle, and reverse the list.
JavaFX Program:
package com.example;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos; import
javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage; import
java.util.LinkedList;
@Override
public void start(Stage primaryStage) {
numbers = new LinkedList<>();
numbers.add(number);
displayNumbers();
}
220280152057
Output:
Before Sorting:
220280152057
After Sorting:
Before Shuffling:
After Shuffling:
220280152057
Before Reversing:
After Reversing:
220280152057
Java Program:
import java.util.*;
PriorityQueue<String> difference =
new PriorityQueue<>(q1);
220280152057
difference.removeAll(q2);
PriorityQueue<String> intersection =
new PriorityQueue<>();
for (String element : q1) {
if (q2.contains(element)) {
intersection.add(element);
}
}
System.out.println("The intersection of two priority
queue is" + intersection);
}
}
Output:
The union of two priority queue is[Blake, George,
Michael, Jim, Katie, Ryan, Michelle, John, Kevin]
The difference of two priority queue is[Blake,
John, Jim, Michael]
The intersection of two priority queue is [George, Kevin]
220280152057
Java Program:
import java.util.*;
Output:
Enter the State
Gujarat
The capital is Gandhinagar
Practical Number-11
1. Aim: (Color and font) Write a program that displays five texts
vertically, as shown in Figure. Set a random color and opacity
for each text and set the font of each text to Times Roman,
bold, italic, and 22 pixels.
JavaFX Program:
package com.example;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene; import
javafx.scene.layout.HBox; import
javafx.scene.layout.VBox; import
javafx.scene.paint.Color; import
javafx.scene.text.Font; import
javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text; import
javafx.stage.Stage;
import java.util.Random;
@Override
public void start(Stage primaryStage)
{ HBox hbox = new HBox();
hbox.setSpacing(10);
hbox.setPadding(new Insets(10));
hbox.setAlignment(Pos.CENTER_LEFT);
Output:
220280152057
2. Aim: (Display a bar chart) Write a program that uses a bar chart
to display the percentages of the overall grade represented by
projects, quizzes, midterm exams, and the final exam, as shown
in Figure 14.46b. Suppose that projects take 20 percent and are
displayed in red, quizzes take 10 percent and are displayed in
blue, midterm exams take 30 percent and are displayed in
green, and the final exam takes 40 percent and is displayed in
orange. Use the Rectangle class to display the bars.
Interested readers may explore the JavaFX BarChart class
for further study.
JavaFX Program:
package com.example;
import javafx.application.Application;
import javafx.stage.Stage; import
javafx.scene.Scene; import
javafx.scene.shape.Rectangle; import
javafx.scene.layout.HBox; import
javafx.scene.layout.VBox; import
javafx.scene.layout.StackPane;
import javafx.geometry.Pos; import
javafx.scene.text.Text; import
javafx.scene.paint.Color; import
javafx.geometry.Insets;
220280152057
// Create 4 rectangles
Rectangle r1 = new Rectangle(0, 0, width, height *
grade[0] / max);
r1.setFill(Color.RED);
Rectangle r2 = new Rectangle(0, 0, width, height *
grade[1] / max);
r2.setFill(Color.BLUE);
Rectangle r3 = new Rectangle(0, 0, width, height *
grade[2] / max);
r3.setFill(Color.GREEN);
220280152057
hBox.getChildren().addAll(getVBox(t1, r1),
getVBox(t2, r2),getVBox(t3, r3), getVBox(t4, r4));
pane.getChildren().add(hBox);
Output:
220280152057
JavaFX Program:
package com.example;
import javafx.application.Application;
import javafx.scene.Scene; import
javafx.scene.layout.Pane; import
javafx.scene.paint.Color; import
javafx.scene.shape.Line; import
javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
import java.util.ArrayList;
@Override
public void start(Stage primaryStage) {
220280152057
line1.endYProperty().bind(rec2.yProperty());
220280152057
shapes.add(line1);
pane.getChildren().addAll(shapes);
220280152057
Output:
220280152057
220280152057
Practical Number-12
1. Aim: (Select a font) Write a program that can dynamically
change the font of a text in a label displayed on a stack pane.
The text can be displayed in bold and italic at the same time.
You can select the font name or font size from combo boxes,
as shown in Figure. The available font names can be obtained
using Font.getFamilies(). The combo box for the font size is
initialized with numbers from 1 to 100.
JavaFX Program:
package com.example;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label; import
javafx.scene.layout.BorderPane; import
javafx.scene.layout.HBox; import
javafx.scene.layout.StackPane; import
javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text; import
javafx.stage.Stage;
220280152057
// Center Text
cbFontSize.getItems().addAll(getSizes());
cbFontSize.setValue((int)text.getFont().getSize());
cbFontSize.setOnAction(e -> {
update();
primaryStage.sizeToScene();
});
220280152057
// Top pane
HBox topPane = new HBox(lblFontFamilies, lblFontSizes);
topPane.setSpacing(5);
topPane.setPadding(new Insets(5));
/ Bottom pane
HBox bottomPane = new HBox(chkBold, chkItalic);
bottomPane.setAlignment(Pos.CENTER);
}
private void update(){
FontWeight fontWeight = (chkBold.isSelected()) ?
FontWeight.BOLD : FontWeight.NORMAL;
FontPosture fontPosture =
(chkItalic.isSelected()) ? FontPosture.ITALIC :
FontPosture.REGULAR;
String fontFamily = cbFontFamilies.getValue();
double size = cbFontSize.getValue();
220280152057
text.setFont(Font.font(fontFamily, fontWeight,
fontPosture, size));
}
return sizes;
}
Output:
220280152057
JavaFX Program:
package com.example;
import javafx.application.Application;
import javafx.animation.PathTransition;
import javafx.animation.Timeline; import
javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.scene.shape.Line;
import javafx.stage.Stage; import
javafx.util.Duration;
PathTransition pt = new
PathTransition(Duration.millis(10000),
new Line(-50, 50, 250, 50), text);
pt.setCycleCount(Timeline.INDEFINITE);
pt.play(); // Start animation
pane.setOnMouseReleased(e -> {
pt.play();
});
Output:
220280152057
JavaFX Program:
package com.example;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.control.Label;
220280152057
}
if (tfSpeed.getText().length() > 0)
animation.setRate(Integer.parseInt(tfSpeed.getText()))
;
animation.play();
});
/ Create a scene and place it in the stage Scene scene =
new Scene(pane, 550, 680);
primaryStage.setTitle("Exercise_16_23"); // Set the stage
title
primaryStage.setScene(scene); // Place the scene in
the stage
primaryStage.show(); // Display the stage
}
Output:
220280152057