0% found this document useful (0 votes)
15 views80 pages

Record Programs (Java) 1

Uploaded by

be22cse45
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views80 pages

Record Programs (Java) 1

Uploaded by

be22cse45
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 80

Linear Search

public class linear search


{
public static void main(string args[]){
{
int[]a={1,5,-2,8,7,11,40,32};
system.out.println("the element is at location"+find(a,7));
system.out.println("the element is at location"+find(a,11));
}
public static in find(int[]a,int key)
{
int 1;
for(i=0;i<a.length;i++)
{
if(a[i]==key)
returni+1;
}
return-1;
}
}
OUTPUT:
Binary Search

public class binsearch


{
public static void main(String args[])
{
int[]a={2,3,6,8,9,13,20};
int key=13; find(a,0,5,key);
}
public static void find(int []a,int low,int high,int key)
{
int mid; if (low>high)
{

System.out.println("Error !the element is not present in list");


}
mid=(low+high)/2; if (key==a[mid])
System.out.println("\nThe element is present at location:"+(mid+1));
else if(key<a[mid]) find(a,low,mid-1,key);
else if(key>a[mid]) find(a,mid+1,high,key);
}

} OUTPUT
Selection Sort

class selectionsort

void sort(int array[])

int n=array.length; for(int i=0;i<n-1;i++)


{
int min_element=i;
for(int j=i+1;j<n;j++)
if(array[j]<array[min_element])
min_element=j;
int temp=array[min_element];
array[min_element]=array[i];
array[i]=temp;
}}
void printarray(int array[])
{ int n=array.length; for(int
i=0;i<n;++i)
System.out.println(array[i]+" ");
System.out.println();
}
public static void main(String args[])
{
selectionsort oh=new selectionsort();
int array[]={15,10,99,53,36};
oh.sort(array);
System.out.println("sorted array");
oh.printarray(array);
}}
OUTPUT
INSERTION SORT

import java.util.Scanner;
public class codescraker
{
public static void main(String args[])
{
int n,i,j,element;
Scanner scan=new Scanner(System.in);
System.out.println("enter the size of array:");
n=scan.nextInt();
int[]arr=new int[n];
System.out.println("enter"+n+"elements:");
for(i=0;i<n;i++)
arr[i]=scan.nextInt();
for(i=1;i<n;i++)
{
element=arr[i];
for(j=(i-1);j>=0&&arr[j]>element;j--)
arr[j+1]=arr[j];
arr[j+1]=element;
}
System.out.println("\nThe new sorted array is:");
for(i=0;i<n;i++)
System.out.println(arr[i]+"");
}
}
OUTPUT:
STACK IMPLEMENTATION

import java.util.*;
class stack{
int top;
int maxsize=5;
int[]stack_array=new int[maxsize];
stack();
{
int top=-1;
}
boolean isempty(){
return(top<0);
}
boolean push(int val)
{
if(top==maxsize-1)
{
System.out.println("stack overflow!!");
return false;
}
else
{
top++;
stack_array[top]=val;
return true;
}
}
boolean pop()
{
if(top==-1)
{
System.out.println("stack underflow");
return false;
}
else
{
System.out.println("\nitem popped:"+stack_array[top-1]);
return true;
}
}
void display()
{
System.out.println("printing stack element..........................................");
for(int i=top;i>=0;i--)
{
System.out.println(stack_array[i]+"");
}
}
}
public class Main{
public static void main(String[] args)
{
stack stck=new stack();
System.out.println("initial stack empty"+stck.isempty());
stck.push(10);
stck.push(20);
stck.push(30);
stck.push(40);
System.out.println("after push operation....");
stck.display();
stck.pop();
stck.pop();
System.out.println("\nafter pop operation....");
stck.display();
}
}
}
OUTPUT:
QUEUE IMPLEMENTATION

class queue
{
private static int front,rear,capacity;
private static int queue[];
queue(int size)
{
front=rear=0;
capacity=size;
queue=new int[capacity];
}
static void queueEnqueue(int item)
{
if(capacity==rear)
{
System.out.println("\nQueue is full\n");
}
else
{
queue[rear]=item;
rear++;
}
}
static void queueDequeue()
{
if(front==rear)
{
System.out.println("\nQueue is empty\n");
}
else
{
for(int i=0;i<rear-1;i++)
queue[i]=queue[i+1];
}
if(rear<capacity)
queue[rear]=0;
rear--;
}
static void queueDisplay()
{
int i;
if(front==rear)
{
System.out.println("\nQueue is empty\n");
}
for(i=front;i<rear;i++)
{
System.out.println(""+queue[i]);
}
}
static void queueFront()
{
if(front==rear)
{
System.out.println("queue is empty\n");
}
System.out.println("\nFront element of the queue:"+queue[front]);
}
}
public class Queue1
{
public static void main(String[] args)
{
queue q=new queue(4);
System.out.println("Initial queue:");
q.queueDisplay();
q.queueEnqueue(10);
q.queueEnqueue(30);
q.queueEnqueue(50);
q.queueEnqueue(70);
System.out.println("Queue after enqueue operation:");
q.queueDisplay();
q.queueFront();
q.queueEnqueue(90);
q.queueDisplay();
q.queueDequeue();
System.out.println("\nQueue after two dequeue operation:");
q.queueDisplay();
q.queueFront();
}
}
OUTPUT:
ABSTRACT CLASS

abstract class shape


{
int a,b;
abstract void printArea();
}
class Rectangle extends shape
{
void printArea()
{
System.out.println("area of rectangle is:"+(a*b)/2);
}
}
class circle extends shape
{
void printArea()
{
System.out.println("area of circle is:"+((22/7)*a*a));
}
}
class Triangle extends shape
{
void printArea()
{
System.out.println("area of triangle:"+(a*b)/2);
}
}
class abs
{
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.a=10;
r.b=20;
r.printArea();
circle c=new circle();
Triangle t=new Triangle();
t.a=30;
t.b=35;
t.printArea();
c.a=2;
c.printArea();
}
}
OUTPUT:
ABSTRACT CLASS TO PERFORM ADDITION

import java.util.Scanner;
abstract class First
{
int a, b, s;
abstract void input();
abstract void add();
abstract void result();
Scanner sc = new Scanner(System.in);
}
class Main extends First
{
void input()
{
System.out.print("Enter two numbers:");
a = sc.nextInt();
b = sc.nextInt();
}
void add()
{
s = a + b;
}
void result() {
System.out.print("Sum of two numbers:" + s);
}
public static void main(String args[]) {
Main st = new Main();
st.input();
st.add();
st.result();
}
}
OUTPUT

Enter two numbers:10 20


Sum of two numbers:30
INTERFACE TO FIND AREA OF SHAPES
interface Shape
{
void input();
void area();
}
class Circle implements Shape
{
int r = 0;
double pi = 3.14, ar = 0;
@Override
public void input()
{
r = 5;
}
@Override
public void area()
{
ar = pi * r * r;
System.out.println("Area of circle:"+ar);
}
}
class Rectangle extends Circle
{
int l = 0, b = 0;
double ar;
public void input()
{
super.input();
l = 6;
b = 4;
}
public void area()
{
super.area();
ar = l * b;
System.out.println("Area of rectangle:"+ar);
}
}
public class Demo
{
public static void main(String[] args)
{
Rectangle obj = new Rectangle();
obj.input();
obj.area();
}
}
OUTPUT

INTERFACE TO CHECK PRIME NUMBER

public class PrimeExample{


public static void main(String args[]){
int i,m=0,flag=0;
int n=3;//it is the number to be checked
m=n/2;
if(n==0||n==1){
System.out.println(n+" is not prime number");
}
else
{
for(i=2;i<=m;i++){
if(n%i==0){
System.out.println(n+" is not prime number");
flag=1;
break;
}
}
if(flag==0) { System.out.println(n+" is prime number"); }
}//end of else
}
}

OUTPUT

3 is prime number

PAY SLIP FOR EMPLOYEE


import java.util.Scanner;

public class EmployeeSalaryCalc

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

Scanner obj=new Scanner(System.in);

Programmer p=new Programmer();

System.out.println("Enter the basic pay of Programmer")

p.getEmployeeDetails(obj.nextDouble());

p.cal();

AssistantProfessor ap=new AssistantProfessor();

System.out.println("Enter the basic pay of Assistant Professor");

ap.getEmployeeDetails(obj.nextDouble());

ap.cal();

AssociateProfessor asp=new AssociateProfessor();

System.out.println("Enter the basic pay of Associate Professor");


asp.getEmployeeDetails(obj.nextDouble());

asp.cal();

Professor prof=new Professor();

System.out.println("Enter the basic pay of Professor");

prof.getEmployeeDetails(obj.nextDouble());

prof.cal();

class Employee{

String employeeName;

int employeeID;

String address;

String mailID;

long mobileNumber;

double da,hra,pf,sc,ns,gs;

Scanner obj=new Scanner(System.in);

void getEmployeeDetails(){

System.out.println("Enter the Employee Name:");

employeeName=obj.nextLine();

System.out.println("Enter the Employee Address:");

address=obj.nextLine();

System.out.println("Enter the Employee Mail ID:");

mailID=obj.nextLine();

System.out.println("Enter the Employee ID:");

employeeID=obj.nextInt(); System.out.println("Enter the Employee Mobile Number:");


mobileNumber=obj.nextLong();

void display()

System.out.println("Employee Name :"+employeeName);

System.out.println("Employee ID :"+employeeID);
System.out.println("Employee Address :"+address);

System.out.println("Employee Mail ID :"+mailID);

System.out.println("Employee Mobile Number:"+mobileNumber);

class Programmer extends Employee

double basicPay;

public double getBasicPay()

return basicPay;

public void setBasicPay(double basicPay)

this.basicPay = basicPay;

void getEmployeeDetails(double bp)

super.getEmployeeDetails();

setBasicPay(bp);

void cal()

da=getBasicPay()*97/100.0;

hra=getBasicPay()*10/100.0;

pf=getBasicPay()*12/100.0;

sc=getBasicPay()*1/100.0;

gs=getBasicPay()+da+hra+pf+sc;

ns=gs-pf-sc;

display();
}

void display()

super.display();

System.out.println("Employee Gross Salary:"+gs);

System.out.println("Employee Net Salary :"+ns);

class AssistantProfessor extends Employee

double basicPay;

public double getBasicPay() {return basicPay;

public void setBasicPay(double basicPay)

this.basicPay = basicPay;

void getEmployeeDetails(double bp){ super.getEmployeeDetails();

setBasicPay(bp);

void cal()

da=getBasicPay()*110/100.0;

hra=getBasicPay()*20/100.0;

pf=getBasicPay()*12/100.0;

sc=getBasicPay()*5/100.0;

gs=getBasicPay()+da+hra+pf+sc;

ns=gs-pf-sc; display();

void display()

{
super.display();

System.out.println("Employee Gross Salary:"+gs);

System.out.println("Employee Net Salary :"+ns);

class AssociateProfessor extends Employee

double basicPay;

public double getBasicPay()

return basicPay;

public void setBasicPay(double basicPay)

this.basicPay = basicPay;

void getEmployeeDetails(double bp)

super.getEmployeeDetails();

setBasicPay(bp);

void cal()

da=getBasicPay()*130/100.0;

hra=getBasicPay()*30/100.0;

pf=getBasicPay()*12/100.0;

sc=getBasicPay()*10/100.0;

gs=getBasicPay()+da+hra+pf+sc;

ns=gs-pf-sc; display();

void display()
{

super.display();

System.out.println("Employee Gross Salary:"+gs);

System.out.println("Employee Net Salary :"+ns);

class Professor extends Employee

this.basicPay = basicPay;

void getEmployeeDetails(double bp)

super.getEmployeeDetails();

setBasicPay(bp);

void cal()

da=getBasicPay()*140/100.0;

hra=getBasicPay()*40/100.0;

pf=getBasicPay()*12/100.0;

sc=getBasicPay()*15/100.0;

gs=getBasicPay()+da+hra+pf+sc;

ns=gs-pf-sc; display();

void display()

super.display();

System.out.println("Employee Gross Salary:"+gs);

System.out.println("Employee Net Salary :"+ns);

}
OUTPUT
Enter the basic pay of Programmer

15000

Enter the Employee Name:

ram

Enter the Employee Address:

56 Ganga Street

Enter the Employee Mail ID:

[email protected]

Enter the Employee ID:

101

Enter the Employee Mobile Number:

9994117284
Employee Name :ram

Employee ID 101

Employee Address :56 Ganga Street

Employee Mail ID :[email protected]

Employee Mobile Number:9994117284

Employee Gross Salary:33000.0

Employee Net Salary :31050.0

Enter the basic pay of Assistant Professor 20000

Enter the Employee Name:

vinu

Enter the Employee Address:

75 public office road

Enter the Employee Mail ID:

[email protected]

Enter the Employee ID:

201

Enter the Employee Mobile Number:

9842321130

Employee Name :vinu

Employee ID 201

Employee Address :75 public office road

Employee Mail ID :[email protected]

Employee Mobile Number:9842321130

Employee Gross Salary:49400.0

Employee Net Salary :46000.0

Enter the basic pay of Associate Professor 30000

Enter the Employee Name:


krish
Enter the Employee Address:
25 neela east street
Enter the Employee Mail ID:
[email protected]
Enter the Employee ID:
301
Enter the Employee Mobile Number:
9578621131

Employee Name :krish


Employee ID 301
Employee Address :25 neela east street
Employee Mail ID :[email protected]
Employee Mobile Number:9578621131
Employee Gross Salary :84600.0
Employee Net Salary :78000.0
Enter the basic pay of Professor 40000

Enter the Employee Name:


vinayagam
Enter the Employee Address:
100 Nehru Street
Enter the Employee Mail ID:
[email protected]
Enter the Employee ID:
401
Enter the Employee Mobile Number:
7904923391
Employee Name :vinayagam
Employee ID 401
Employee Address :100 Nehru Street
Employee Mail ID :[email protected]
Employee Mobile Number:7904923391
Employee Gross Salary:122800.0
Employee Net Salary :112000.0

USER DEFINED EXPECTATION

import java.util.Scanner;
class NegativeAmtException extends Exception
{
String msg;
NegativeAmtException(String msg)
{
this.msg=msg;
}
public String toString()
{
return msg;
}
}
public class userdefined
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter Amount:");
int a=s.nextInt();
try
{
if(a<0)
{
throw new NegativeAmtException("Invalid Amount");
}
System.out.println("Amount Deposited");
}
catch(NegativeAmtException e)
{
System.out.println(e);
}
}
}
OUTPUT
MULTI THREADED APPLICATIONS

import java.util.*;
// class for Even Number
class EvenNum implements Runnable {
public int a;
public EvenNum(int a) {
this.a = a;
}
public void run() {
System.out.println("The Thread "+ a +" is EVEN and Square of " + a + " is : " + a * a);
}
} // class for Odd Number
class OddNum implements Runnable {
public int a;
public OddNum(int a) {
this.a = a;
}
public void run() {
System.out.println("The Thread "+ a +" is ODD and Cube of " + a + " is: " + a * a * a);
}
}
// class to generate random number
class RandomNumGenerator extends Thread {
public void run() {
int n = 0;
Random rand = new Random();
try {
for (int i = 0; i < 10; i++) {
n = rand.nextInt(20);
System.out.println("Generated Number is " + n);
// check if random number is even or odd
if (n % 2 == 0) {
Thread thread1 = new Thread(new EvenNum(n));
thread1.start();
}
else {
Thread thread2 = new Thread(new OddNum(n));
thread2.start();
}
// thread wait for 1 second
Thread.sleep(1000);
System.out.println(" ");
}
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
// Driver class
public class MultiThreadRandOddEven {
public static void main(String[] args) {
RandomNumGenerator rand_num = new RandomNumGenerator();
rand_num.start();
}
}

OUTPUT
FILE OPERATION
FILE CREATION
import java.io.File;
// Importing the IOException class for handling errors

import java.io.IOException;

class CreateFile {

public static void main(String args[]) {

try {

// Creating an object of a file

File f0 = new File("D:File1.txt");

if (f0.createNewFile()) {

System.out.println("File " + f0.getName() + " is created successfully.");

else

System.out.println("File is already exist in the directory.");

} catch (IOException exception) {

System.out.println("An unexpected error is occurred.");

exception.printStackTrace();

}}

OUTPUT

DISPLAY FILE PROPERTIES

import java.util.Scanner;
import java.io.File;
class fileDemo{
public static void main(String[] args){
System.out.println("Enter the file name:");
Scanner input = new Scanner(System.in);
String s = input.nextLine();
File f1=new File(s);
System.out.println("-------------------------");
System.out.println("File Name: " +f1.getName());
System.out.println("Path: " +f1.getPath());
System.out.println("Abs Path: " +f1.getAbsolutePath());
System.out.println("This file: " +(f1.exists()?"Exists":"Does not exists"));
System.out.println("File: " +f1.isFile());
System.out.println("Directory: " +f1.isDirectory());
System.out.println("Readable: " +f1.canRead());
System.out.println("Writable: " +f1.canWrite());
System.out.println("Absolute: " +f1.isAbsolute());
System.out.println("File Size: " +f1.length()+ "bytes");
System.out.println("Is Hidden: " +f1.isHidden());
}
}

OUTPUT
WRITE CONTENT INTO FILE

import java.io.File;
import java.io.FileOutputStream;
import java.util.Scanner;
public class WriteFile {
public static void main(String args[]) {
final String fileName = "file.txt";
try {
File objFile = new File(fileName);
if (objFile.exists() == false) {
if (objFile.createNewFile()) {
System.out.println("File created successfully.");
} else {
System.out.println("File creation failed!!!");
System.exit(0);
}
}
//writting data into file
String text;
Scanner SC = new Scanner(System.in);
System.out.println("Enter text to write into file: ");
text = SC.nextLine();
//object of FileOutputStream
FileOutputStream fileOut = new FileOutputStream(objFile);
//convert text into Byte and write into file
fileOut.write(text.getBytes());
fileOut.flush();
fileOut.close();
System.out.println("File saved.");
} catch (Exception Ex) {
System.out.println("Exception : " + Ex.toString());
}
}
}

OUTPUT
READ CONTENT INTO FILE

import java.io.File;
import java.io.FileInputStream;
public class ReadFile {
public static void main(String args[]) {
final String fileName = "file.txt";
try
{
File objFile = new File(fileName);
if (objFile.exists() == false) {
System.out.println("File does not exist!!!");
System.exit(0);
}
String text;
int val;
FileInputStream fileIn = new FileInputStream(objFile);
//read text from file
System.out.println("Content of the file is: ");
while ((val = fileIn.read()) != -1) {
System.out.print((char) val);
}
System.out.println();
fileIn.close();
} catch (Exception Ex) {
System.out.println("Exception : " + Ex.toString());
}
}
}

OUTPUT
GENERIC CLASSES

import java.util.ArrayList;
public class UpperBoundWildcard {
private static Double add(ArrayList<? extends Number> num) {
double sum=0.0;
for(Number n:num)
{
sum = sum+n.doubleValue();
}
return sum;
}
public static void main(String[] args) {
ArrayList<Integer> l1=new ArrayList<Integer>();
l1.add(10);
l1.add(20);
System.out.println("displaying the sum= "+add(l1));

ArrayList<Double> l2=new ArrayList<Double>();


l2.add(30.0);
l2.add(40.0);
System.out.println("displaying the sum= "+add(l2));
}
}

OUTPUT
DEVELOP APPLICATIONS USING JAVAFX CONTROLS

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.ListView;
import javafx.scene.control.RadioButton;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.ToggleButton;
import javafx.stage.Stage;
public class Registration extends Application {
@Override
public void start(Stage stage) {
//Label for name
Text nameLabel = new Text("Name");
//Text field for name
TextField nameText = new TextField();
//Label for date of birth
Text dobLabel = new Text("Date of birth");
//date picker to choose date
DatePicker datePicker = new DatePicker();
//Label for gender
Text genderLabel = new Text("gender");
//Toggle group of radio buttons
ToggleGroup groupGender = new ToggleGroup();
RadioButton maleRadio = new RadioButton("male");
maleRadio.setToggleGroup(groupGender);
RadioButton femaleRadio = new RadioButton("female");
femaleRadio.setToggleGroup(groupGender);
//Label for reservation
Text reservationLabel = new Text("Reservation");
//Toggle button for reservation
ToggleButton Reservation = new ToggleButton();
ToggleButton yes = new ToggleButton("Yes");
ToggleButton no = new ToggleButton("No");
ToggleGroup groupReservation = new ToggleGroup();
yes.setToggleGroup(groupReservation);
no.setToggleGroup(groupReservation);
//Label for technologies known
Text technologiesLabel = new Text("Technologies Known");
//check box for education
CheckBox javaCheckBox = new CheckBox("Java");
javaCheckBox.setIndeterminate(false);
//check box for education
CheckBox dotnetCheckBox = new CheckBox("DotNet");
javaCheckBox.setIndeterminate(false);
//Label for education
Text educationLabel = new Text("Educational qualification");
//list View for educational qualification
ObservableList<String> names = FXCollections.observableArrayList(
"Engineering", "MCA", "MBA", "Graduation", "MTECH", "Mphil", "Phd");
ListView<String> educationListView = new ListView<String>(names);
//Label for location
Text locationLabel = new Text("location");
//Choice box for location
ChoiceBox locationchoiceBox = new ChoiceBox();
locationchoiceBox.getItems().addAll
("Hyderabad", "Chennai", "Delhi", "Mumbai", "Vishakhapatnam");
//Label for register
Button buttonRegister = new Button("Register");
//Creating a Grid Pane
GridPane gridPane = new GridPane();
//Setting size for the pane
gridPane.setMinSize(500, 500);
//Setting the padding
gridPane.setPadding(new Insets(10, 10, 10, 10));
//Setting the vertical and horizontal gaps between the columns
gridPane.setVgap(5);
gridPane.setHgap(5);
//Setting the Grid alignment
gridPane.setAlignment(Pos.CENTER);
//Arranging all the nodes in the grid
gridPane.add(nameLabel, 0, 0);
gridPane.add(nameText, 1, 0);
gridPane.add(dobLabel, 0, 1);
gridPane.add(datePicker, 1, 1);
gridPane.add(genderLabel, 0, 2);
gridPane.add(maleRadio, 1, 2);
gridPane.add(femaleRadio, 2, 2);
gridPane.add(reservationLabel, 0, 3);
gridPane.add(yes, 1, 3);
gridPane.add(no, 2, 3);
gridPane.add(technologiesLabel, 0, 4);
gridPane.add(javaCheckBox, 1, 4);
gridPane.add(dotnetCheckBox, 2, 4);
gridPane.add(educationLabel, 0, 5);
gridPane.add(educationListView, 1, 5);
gridPane.add(locationLabel, 0, 6);
gridPane.add(locationchoiceBox, 1, 6);
gridPane.add(buttonRegister, 2, 8);
//Styling nodes
buttonRegister.setStyle("-fx-background-color: darkslateblue; -fx-textfill: white;");
nameLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
dobLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
genderLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
reservationLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
technologiesLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
educationLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
locationLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
//Setting the back ground color
gridPane.setStyle("-fx-background-color: BEIGE;");
//Creating a scene object
Scene scene = new Scene(gridPane);
//Setting title to the Stage
stage.setTitle("Registration Form");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}

OUTPUT
DEVELOP APPLICATIONS USING JAVAFX LAYOUTS

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.FlowPane;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.geometry.Insets;
public class ShowFlowPane extends Application {
@Override
public void start(Stage primaryStage) {
FlowPane pane = new FlowPane();
pane.setPadding(new Insets(11, 12, 13, 14));
pane.setHgap(5);
pane.setVgap(5);
// Place nodes in the pane
pane.getChildren().addAll(new Label("First Name:"),
new TextField(), new Label("MI:"));
TextField tfMi = new TextField();
tfMi.setPrefColumnCount(1);
pane.getChildren().addAll(tfMi, new Label("Last Name:"),
new TextField());
// Create a scene and place it in the stage
Scene scene = new Scene(pane, 210, 150);
primaryStage.setTitle("ShowFlowPane");
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
public static void main(String[] args) {
launch(args);
}
}

OUTPUT
DEVELOP APPLICATIONS USING JAVAFX MENUS

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.geometry.Pos;
public class MenuDemo extends Application {
private TextField tfNumber1 = new TextField();
private TextField tfNumber2 = new TextField();
private TextField tfResult = new TextField();
@Override
public void start(Stage primaryStage) {
MenuBar menuBar = new MenuBar();
Menu menuOperation = new Menu("Operation");
Menu menuExit = new Menu("Exit");
menuBar.getMenus().addAll(menuOperation, menuExit);
MenuItem menuItemAdd = new MenuItem("Add");
MenuItem menuItemSubtract = new MenuItem("Subtract");
MenuItem menuItemMultiply = new MenuItem("Multiply");
MenuItem menuItemDivide = new MenuItem("Divide");
menuOperation.getItems().addAll(menuItemAdd, menuItemSubtract,
menuItemMultiply, menuItemDivide);
MenuItem menuItemClose = new MenuItem("Close");
menuExit.getItems().add(menuItemClose);
menuItemAdd.setAccelerator(
KeyCombination.keyCombination("Ctrl+A"));
menuItemSubtract.setAccelerator(
KeyCombination.keyCombination("Ctrl+S"));
menuItemMultiply.setAccelerator(
KeyCombination.keyCombination("Ctrl+M"));
menuItemDivide.setAccelerator(
KeyCombination.keyCombination("Ctrl+D"));
HBox hBox1 = new HBox(5);
tfNumber1.setPrefColumnCount(2);
tfNumber2.setPrefColumnCount(2);
tfResult.setPrefColumnCount(2);
hBox1.getChildren().addAll(new Label("Number 1:"), tfNumber1,
new Label("Number 2:"), tfNumber2, new Label("Result:"),
tfResult);
hBox1.setAlignment(Pos.CENTER);
HBox hBox2 = new HBox(5);
Button btAdd = new Button("Add");
Button btSubtract = new Button("Subtract");
Button btMultiply = new Button("Multiply");
Button btDivide = new Button("Divide");
hBox2.getChildren().addAll(btAdd, btSubtract, btMultiply, btDivide);
hBox2.setAlignment(Pos.CENTER);
VBox vBox = new VBox(10);
vBox.getChildren().addAll(menuBar, hBox1, hBox2);
Scene scene = new Scene(vBox, 300, 250);
primaryStage.setTitle("MenuDemo"); // Set the window title
primaryStage.setScene(scene); // Place the scene in the window
primaryStage.show(); // Display the window
// Handle menu actions
menuItemAdd.setOnAction(e -> perform('+'));
menuItemSubtract.setOnAction(e -> perform('-'));
menuItemMultiply.setOnAction(e -> perform('*'));
menuItemDivide.setOnAction(e -> perform('/'));
menuItemClose.setOnAction(e -> System.exit(0));
// Handle button actions
btAdd.setOnAction(e -> perform('+'));
btSubtract.setOnAction(e -> perform('-'));
btMultiply.setOnAction(e -> perform('*'));
btDivide.setOnAction(e -> perform('/'));
}
private void perform(char operator) {
double number1 = Double.parseDouble(tfNumber1.getText());
double number2 = Double.parseDouble(tfNumber2.getText());
double result = 0;
switch (operator) {
case '+': result = number1 + number2; break;
case '-': result = number1 - number2; break;
case '*': result = number1 * number2; break;
case '/': result = number1 / number2; break;
}
tfResult.setText(result + "");
};
public static void main(String[] args) {
launch(args);
}
}

OUTPUT
SCIENTIFIC CALCULATOR
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class ScientificCalculator extends JFrame implements ActionListener {
JTextField tfield;
double temp, temp1, result, a;
static double m1, m2;
int k = 1, x = 0, y = 0, z = 0;
char ch;
JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, zero, clr, pow2, pow3, exp,
fac, plus, min, div, log, rec, mul, eq, addSub, dot, mr, mc, mp,
mm, sqrt, sin, cos, tan;
Container cont;
JPanel textPanel, buttonpanel;
ScientificCalculator() {
cont = getContentPane();
cont.setLayout(new BorderLayout());
JPanel textpanel = new JPanel();
tfield = new JTextField(25);
tfield.setHorizontalAlignment(SwingConstants.RIGHT);
tfield.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent keyevent) {
char c = keyevent.getKeyChar();
if (c >= '0' && c <= '9') {
} else {
keyevent.consume();
}
}
});
textpanel.add(tfield);
buttonpanel = new JPanel();
buttonpanel.setLayout(new GridLayout(8, 4, 2, 2));
boolean t = true;
mr = new JButton("MR");
buttonpanel.add(mr);
mr.addActionListener(this);
mc = new JButton("MC");
buttonpanel.add(mc);
mc.addActionListener(this);
mp = new JButton("M+");
buttonpanel.add(mp);
mp.addActionListener(this);
mm = new JButton("M-");
buttonpanel.add(mm);
mm.addActionListener(this);
b1 = new JButton("1");
buttonpanel.add(b1);
b1.addActionListener(this);
b2 = new JButton("2");
buttonpanel.add(b2);
b2.addActionListener(this);
b3 = new JButton("3");
buttonpanel.add(b3);
b3.addActionListener(this);
b4 = new JButton("4");
buttonpanel.add(b4);
b4.addActionListener(this);
b5 = new JButton("5");
buttonpanel.add(b5);
b5.addActionListener(this);
b6 = new JButton("6");
buttonpanel.add(b6);
b6.addActionListener(this);
b7 = new JButton("7");
buttonpanel.add(b7);
b7.addActionListener(this);
b8 = new JButton("8");
buttonpanel.add(b8);
b8.addActionListener(this);
b9 = new JButton("9");
buttonpanel.add(b9);
b9.addActionListener(this);
zero = new JButton("0");
buttonpanel.add(zero);
zero.addActionListener(this);
plus = new JButton("+");
buttonpanel.add(plus);
plus.addActionListener(this);
min = new JButton("-");
buttonpanel.add(min);
min.addActionListener(this);
mul = new JButton("*");
buttonpanel.add(mul);
mul.addActionListener(this);
div = new JButton("/");
div.addActionListener(this);
buttonpanel.add(div);
addSub = new JButton("+/-");
buttonpanel.add(addSub);
addSub.addActionListener(this);
dot = new JButton(".");
buttonpanel.add(dot);
dot.addActionListener(this);
eq = new JButton("=");
buttonpanel.add(eq);
eq.addActionListener(this);
rec = new JButton("1/x");
buttonpanel.add(rec);
rec.addActionListener(this);
sqrt = new JButton("Sqrt");
buttonpanel.add(sqrt);
sqrt.addActionListener(this);
log = new JButton("log");
buttonpanel.add(log);
log.addActionListener(this);
sin = new JButton("SIN");
buttonpanel.add(sin);
sin.addActionListener(this);
cos = new JButton("COS");
buttonpanel.add(cos);
cos.addActionListener(this);
tan = new JButton("TAN");
buttonpanel.add(tan);
tan.addActionListener(this);
pow2 = new JButton("x^2");
buttonpanel.add(pow2);
pow2.addActionListener(this);
pow3 = new JButton("x^3");
buttonpanel.add(pow3);
pow3.addActionListener(this);
exp = new JButton("Exp");
exp.addActionListener(this);
buttonpanel.add(exp);
fac = new JButton("n!");
fac.addActionListener(this);
buttonpanel.add(fac);
clr = new JButton("AC");
buttonpanel.add(clr);
clr.addActionListener(this);
cont.add("Center", buttonpanel);
cont.add("North", textpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if (s.equals("1"))
{
if (z == 0)
{
tfield.setText(tfield.getText()+ "1");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText()+ "1");
z= 0;
}
}
if (s.equals("2"))
{
if (z == 0)
{
tfield.setText(tfield.getText()+ "2");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText()+ "2");
z= 0;
}
}
if (s.equals("3"))
{
if (z == 0)
{
tfield.setText(tfield.getText()+ "3");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText()+ "3");
z= 0;
}
}
if (s.equals("4"))
{
if (z == 0)
{
tfield.setText(tfield.getText()+ "4");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText()+ "4");
z= 0;
}
}
if (s.equals("5"))
{
if (z == 0)
{
tfield.setText(tfield.getText()+ "5");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText()+ "5");
z= 0;
}
}
if (s.equals("6"))
{
if (z == 0)
{
tfield.setText(tfield.getText()+ "6");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText()+ "6");
z= 0;
}
}
if (s.equals("7")) {
if (z == 0) {
tfield.setText(tfield.getText() + "7");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText() + "7");
z = 0;
}
}
if (s.equals("8")) {
if (z == 0) {
tfield.setText(tfield.getText() + "8");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText() + "8");
z = 0;
}
}
if (s.equals("9"))
{
if (z == 0)
{
tfield.setText(tfield.getText() + "9");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText() + "9");
z = 0;
}
}
if (s.equals("0"))
{
if (z == 0) {
tfield.setText(tfield.getText() + "0");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText() + "0");
z = 0;
}
}
if (s.equals("AC")) {
tfield.setText("");
x = 0;
y = 0;
z = 0;
}
if (s.equals("log"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a = Math.log(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("1/x")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = 1 / Double.parseDouble(tfield.getText());
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("Exp"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a = Math.exp(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("x^2"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a = Math.pow(Double.parseDouble(tfield.getText()), 2);
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("x^3"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
} else {
a = Math.pow(Double.parseDouble(tfield.getText()), 3);
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("+/-"))
{
if (x == 0)
{
tfield.setText("-" + tfield.getText());
x = 1;
}
else
{
tfield.setText(tfield.getText());
}
}
if (s.equals("."))
{
if (y == 0)
{
tfield.setText(tfield.getText() + ".");
y = 1;
}
else
{
tfield.setText(tfield.getText());
}
}
if (s.equals("+"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
temp = 0;
ch = '+';
}
else
{
temp = Double.parseDouble(tfield.getText());
tfield.setText("");
ch = '+';
y = 0;
x = 0;
}
tfield.requestFocus();
}
if (s.equals("-"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
temp = 0;
ch = '-';
}
else
{
x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText());
tfield.setText("");
ch = '-';
}
tfield.requestFocus();
}
if (s.equals("/"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
temp = 1;
ch = '/';
}
else
{
x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText());
ch = '/';
tfield.setText("");
}
tfield.requestFocus();
}
if (s.equals("*"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
temp = 1;
ch = '*';
}
else
{
x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText()); //string to double
ch = '*';
tfield.setText("");
}
tfield.requestFocus();
}
if (s.equals("MC"))
{
m1 = 0;
tfield.setText("");
}
if (s.equals("MR"))
{
tfield.setText("");
tfield.setText(tfield.getText() + m1);
}
if (s.equals("M+"))
{
if (k == 1)
{
m1 = Double.parseDouble(tfield.getText());
k++;
}
else
{
m1 += Double.parseDouble(tfield.getText());
tfield.setText("" + m1);
}
}
if (s.equals("M-"))
{
if (k == 1)
{
m1 = Double.parseDouble(tfield.getText());
k++;
}
else
{
m1 -= Double.parseDouble(tfield.getText());
tfield.setText("" + m1);
}
}
if (s.equals("Sqrt"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a = Math.sqrt(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("SIN"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a = Math.sin(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("COS"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a = Math.cos(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("TAN"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a = Math.tan(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("="))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
temp1 = Double.parseDouble(tfield.getText());
switch (ch)
{
case '+':
result = temp + temp1;
break;
case '-':
result = temp - temp1;
break;
case '/':
result = temp / temp1;
break;
case '*':
result = temp * temp1;
break;
}
tfield.setText("");
tfield.setText(tfield.getText() + result);
z = 1;
}
}
if (s.equals("n!"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a = fact(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
tfield.requestFocus();
}
double fact(double x)
{
int er = 0;
if (x < 0)
{
er = 20;
return 0;
}
double i, s = 1;
for (i = 2; i <= x; i += 1.0)
s *= i;
return s;
}
public static void main(String args[])
{
try
{
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (Exception e)
{
}
ScientificCalculator f = new ScientificCalculator();
f.setTitle("ScientificCalculator");
f.pack();
f.setVisible(true);
}
}

OUTPUT

You might also like