Thursday, April 9, 2020
OOP Program-25
(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.
Program Code:
import java.io.*;
import java.security.InvalidParameterException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.TreeSet;
import java.util.Collections;
import java.util.Iterator;
public class OOP_25
{
public static void main(String[] args) throws FileNotFoundException
{
if (args.length != 1)
throw new InvalidParameterException("Usage: fullFilePathName");
File file = new File(args[0]);
if (!file.isFile())
throw new FileNotFoundException(file + " is not a file.");
try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file)), 10000))
{
String inputS;
StringBuilder sb = new StringBuilder(10000);
while ((inputS = in.readLine()) != null)
sb.append(inputS);
String[] words = sb.toString().split("\\s+");
TreeSet<String> ndWords = new TreeSet<>(Arrays.asList(words));
Iterator<String> itr = ndWords.descendingIterator();
String s;
while (itr.hasNext())
{
s = itr.next();
System.out.println(s);
}
}
catch (IOException e)
{
e.printStackTrace();
System.exit(0);
}
}
}
ABC, PQR, GTU, BE, Semester-4, OOP-1,
SubjectCode:3140705, COLLEGE,
Output:
OOP Program-24
(24) Define MYPriorityQueue class that
extends Priority Queue to implement the Cloneable interface and implement
the clone() method to clone a priority queue.
Program Code:
public class OOP_24
{
public static void main(String[] args)
{
MyPriorityQueue<String> queue = new MyPriorityQueue<>();
queue.offer("101");
queue.offer("201");
queue.offer("301");
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:
OOP Program-23
(23) Write a generic method that
returns the minimum elements in a two dimensional array.
Program Code:
public class OOP_23
{
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("minimum = " + min(list));
}
public static <E extends Comparable<E>> E min(E[][] list)
{
E min = list[0][0];
for (E[] elements : list)
{
for (E element : elements)
{
if (element.compareTo(min) < 0)
{
min = element;
}
}
}
return min;
}
}
Output:
OOP Program-22
(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.
Program Code-1: Write a recursive method that returns the smallest integer in an array.
public class OOP_22
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter five integers: ");
int[] list = new int[5];
for (int i = 0; i < list.length; i++)
{
list[i] = input.nextInt();
}
System.out.println("The smallest element is " + min(list));
}
public static int min(int[] list)
{
int min = list[list.length - 1];
int index = list.length - 1;
return min(list, index, min);
}
private static int min(int[] list, int index, int min)
{
if (index < 0)
{
return min;
}
else if (list[index] < min)
{
return min(list, index - 1, list[index]);
}
else
{
return min(list, index - 1, min);
}
}
}
Output-1:
Program Code-2:Write a test program that prompts the user to enter an integer and display its product.
import java.util.Scanner;
public class OOP_22_2
{
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-2:
OOP Program-21
(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
exists. Write 150 integers created randomly into the file
using Text I/O. Integers are separated by space.
import java.io.*;

Program Code:
import java.util.Scanner;
public class OOP_21
{
public static void main(String[] args)
{
try (
PrintWriter pw = new PrintWriter(new FileOutputStream(new File("123.txt"), true));
) {
pw.print(" Semester-4 & Subject= OOP-1 ");
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:
OOP Program-20
(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 Code:
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 OOP_20 extends Application
{
protected Text text = new Text(50, 50, "CodingKick");
@Override
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("OOP_20");
primaryStage.setScene(scene);
primaryStage.show();
}
}
Output:
2)Use the radio button to change the color of message:
OOP Program-19
(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.
import javafx.application.Application;
2) Displays the color of a circle as red when the mouse button is pressed:

Program Code:
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class OOP_19 extends Application
{
@Override
public void start(Stage primaryStage)
{
double width = 450;
double height = 450;
Circle c = new Circle(width / 2, height / 2, Math.min(width, height) / 10, Color.BLUE);
c.setStroke(Color.WHITE);
StackPane pane = new StackPane(c);
primaryStage.setScene(new Scene(pane, width, height));
pane.setOnMousePressed(e -> c.setFill(Color.RED));
pane.setOnMouseReleased(e -> c.setFill(Color.BLUE));
primaryStage.setTitle("Click circle..");
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
Output:
1) Displays the color of a circle as blue when the mouse button is released.
2) Displays the color of a circle as red when the mouse button is pressed:

OOP Program-18
(18) Write a program that moves a circle up, down, left or right using arrow keys.
import javafx.application.Application;
2)
Circle is moved after we press up, down, left or right arrow keys:

Program Code:
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:
1) Default output:
Circle is moved after we press up, down, left or right arrow keys:
OOP Program-17
(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.
import javafx.application.Application;
Program Code:
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/x1.gif")), j, i);
else if (n == 1)
pane.add(new ImageView(new Image("image/o1.gif")), j, i);
else
continue;
}
}
Scene scene = new Scene(pane, 120, 130);
primaryStage.setTitle("OOP_17");
primaryStage.setScene(scene);
primaryStage.show();
}
}
Output:
OOP Program-16
(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.
Hint: Read the decimal number as a string, extract the integer part and fractional part from the string.
Program Code:
import java.math.BigInteger;
public class OOP_16
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Double d;
System.out.print("Enter a decimal number= ");
String[] decimal = input.nextLine().split("[.]");
BigInteger b1 = new BigInteger(decimal[0]);
BigInteger b2 = new BigInteger((decimal[1]));
if(decimal[0].charAt(0) == '-')
{
d = b1.doubleValue() - (b2.intValue() / Math.pow(10, decimal[1].length()));
}
else
{
d = b1.doubleValue() + (b2.intValue() / Math.pow(10, decimal[1].length()));
}
System.out.println("The fraction number is= " +d);
}
}
Output:
OOP Program-15
(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.
Program Code:
public class OOP_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("Decimal Value = " + bin2Dec(str));
}
catch(NumberFormatException e)
{
System.out.println(e);
}
}
}
Output:
OOP Program-14
(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.
Program Code:
import java.util.Date;
public class OOP_14
{
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(" \n "+(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:
OOP Program-13
(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.
Program Code:
public class OOP_13
{
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:
Subscribe to:
Posts (Atom)