Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

JAva 4

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 40

12202040501019 Dharmik Rabadiya

Practical 5
1. Define two nested classes: Processor and RAM, inside the outer
class: CPU with following data members
class CPU {
double price;
class Processor{
double cores;
double catch()
String manufacturer;
double getCache()
void displayProcesorDetail()
}
protected class RAM { // nested protected class
double memory;
String manufacturer;
Double clockSpeed;
double getClockSpeed()
void displayRAMDetail()
}
}
Write appropriate Constructor and create instance of Outer and inner
class and call the methods in main function
12202040501019 Dharmik Rabadiya

Code:
import java.util.Scanner;
class CPU {
double price;
CPU(double p){
price=p;
}
public void displayprice()
{
System.out.println("Price:"+price);
}
class Processor{ // nested class
double cores;
String manufacturer;
int cache;

Processor(double c, String m)
{
cores=c;
manufacturer=m;

}
public void getCache()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter Cache");
cache= sc.nextInt();
12202040501019 Dharmik Rabadiya

}
public void displayProcesorDetail(){
System.out.println("Core:"+ cores);
System.out.println("manufacturer:"+ manufacturer);
System.out.println("cache:"+ cache);

}
}
class RAM{ // nested protected class
// members of protected nested class
double memory;
String manufacturer;
Double clockSpeed;
RAM(double m,String man)
{
memory=m;
manufacturer=man;
}
public void getClockSpeed()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter ClockSpeed");
clockSpeed= sc.nextDouble();
}
public void displayRAMDetail(){
System.out.println("memory:"+ memory);
System.out.println("manufacturer:"+ manufacturer);
System.out.println("clockSpeed:"+ clockSpeed);
}
}
12202040501019 Dharmik Rabadiya

class MainCPU{
public static void main(String args[]){
CPU c = new CPU(50000.0);
CPU.Processor p=c.new Processor(5.0,"Intel");
CPU.RAM r=c.new RAM(16.0,"Intel");

c.displayprice();
p.getCache();
p.displayProcesorDetail();
r.getClockSpeed();
r.displayRAMDetail();
}}

Output:
12202040501019 Dharmik Rabadiya

2. Write a program to demonstrate usage of static inner class, local


inner class and anonymous inner class
Code:
import java.util.Scanner;
class Outer {
public void display()
{
System.out.println("Inside Outer class");
}

class NInner{
public void display()
{
System.out.println("Inside Local Inner class");
}
}

static class InnerStatic{


public void display()
{
System.out.println("Inside Static Inner class");
}
}
}

interface AnonymousInner{
public void display();
}
12202040501019 Dharmik Rabadiya

class MainInner{
public static void main(String args[])
{
Outer o= new Outer();
o.display();

Outer.NInner n =o.new NInner();


n.display();

Outer.InnerStatic s=new Outer.InnerStatic();


s.display();
AnonymousInner a = new AnonymousInner(){
public void display(){
System.out.println("Inside AnonymousInner Inner class");
}
};
a.display();
}
}

Output:

Practical 6
12202040501019 Dharmik Rabadiya

Q-1 Declare a class InvoiceDetail which accepts a type parameter


which is of
type Number with following data members
class InvoiceDetail <N extends Number> {
private String invoiceName;
private N amount;
private N Discount;
write getters, setters and constructors } Call the methods in Main
class.
Code:
import java.util.*;
class InvoiceDetail<N extends Number> {
private String invoiceName;
private N amount;
private N discount;
InvoiceDetail() {}
InvoiceDetail(String invoiceName, N amount, N discount) {
this.amount = amount;
this.discount = discount;
this.invoiceName = invoiceName; }
public void setInvoiceName(String invoiceName) {
this.invoiceName = invoiceName;
}
public String getInvoiceName() {
return invoiceName;
}
public void setAmount(N amount) {
this.amount = amount; }
public N getAmount() { return amount; }
public void setDiscount(N discount) {
12202040501019 Dharmik Rabadiya

this.discount = discount;
}
public N getDiscount() { return discount; }
public void display() {
System.out.println("Invoice Name : " + invoiceName);
System.out.println("Amount : " + amount);
System.out.println("Discount : " + discount + "%");
}}
public class InvoiceMain {
public static void main(String[] args) {
InvoiceDetail<Integer> invoice1 = new InvoiceDetail<Integer>();
invoice1.setInvoiceName("Shrey");
invoice1.setAmount(50000);
invoice1.setDiscount(50);
invoice1.display();
InvoiceDetail<Float> invoice2 = new InvoiceDetail<Float>();
invoice2.setInvoiceName("ABC");
invoice2.setAmount(694.56f);
invoice2.setDiscount(50.5f);
invoice2.display();
}}

Output:

2. Implement Generic Stack


12202040501019 Dharmik Rabadiya

import java.util.*;
class GenericStack<T> {
Scanner scan = new Scanner(System.in);
int top = -1;
int size;
T t;
List<T> Stack;
GenericStack(int size) {
Stack = new ArrayList<T>(size);
this.size = size;
}
void push(T item) {
// T item = (T) scan.next();
top++;
Stack.add(top, item);
}
public T pop() {
if (top == -1) {
throw new IllegalStateException("Stack is Empty");
}
return Stack.remove(top--);
}
public T peek() {
if (top == -1) {
throw new IllegalStateException("Stack is Empty");
}
return Stack.get(top);
}
public void display() {
System.out.println("Stack elements are:");
12202040501019 Dharmik Rabadiya

if (top == -1) {
throw new IllegalStateException("Stack is Empty");
}
for (int i = top; i >= 0; i--) {
System.out.println("Stack[" + i + "] : " + Stack.get(i));
}
}
}
public class StackMain {
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
int ch;
GenericStack<Character> stack = new GenericStack<>(5);
do {
System.out.println("1.Push\n2.PoP\n3.Peek\n4.Display Stack\n5.Exit");
ch = scan.nextInt();
switch (ch) {
case 1:
stack.push('A');
stack.push('B');
stack.push('C');
stack.push('D');
break;
case 2:
System.out.println("Poped Element is : " + stack.pop());
break;
case 3:
System.out.println("Top Element is : " + stack.peek());
break;
case 4:
12202040501019 Dharmik Rabadiya

stack.display();
break;
case 5:
System.exit(0);
break;
} } while (ch != 5);
}}

Output:

3. Write a program to sort the object of Book class using


comparable and comparator interface. (Book class consist of book
id, title, author and publisher as data members).
12202040501019 Dharmik Rabadiya

Code:
import java.util.*;
class Book implements Comparable<Book> {
String bookTitle;
String bookAuthor;
String bookPublisher;
int bookID;
public Book(String bookTitle, String bookAuthor, String bookPublisher, int bookID) {
this.bookTitle = bookTitle;
this.bookAuthor = bookAuthor;
this.bookPublisher = bookPublisher;
this.bookID = bookID; }
@Override
public String toString() {
return ( "Book [ bookID=" +bookID +", bookTitle=" +bookTitle +", bookAuthor=" +
bookAuthor +", bookPublisher=" + bookPublisher + "]" ); }
@Override
public int compareTo(Book o) {
return this.bookTitle.compareTo(o.bookTitle);
}}
public class BooksMain {
Scanner s= new Scanner(System.in);
public static void main(String[] args) {
ArrayList<Book> bookList = new ArrayList<>();
int ch;
bookList.add(new Book("Java Programming", " HG ", "ABC", 53));
bookList.add(new Book("Technical writing", " CZ ", "XYZ", 24));
bookList.add(new Book("Computer Organization", " SV ", "PQR", 91));
for (Book book : bookList) { System.out.println(book); }
do {
System.out.println("\n1.Sort Using Comparator\n2.Sort Using Comparable\n3.Exit");
12202040501019 Dharmik Rabadiya

ch = s.nextInt();
switch (ch) {
case 1: System.out.println(“Sorting Using Comparator");
Comparator<Book> cmp = new Comparator<Book>() {
@Override
public int compare(Book i, Book j) {
if (i.bookID > j.bookID) return 1;
else return -1; } };
Collections.sort(bookList, cmp);
for (Book book : bookList) { System.out.println(book); }
break;
case 2: System.out.println(“Sorting Using Comparable ");
Collections.sort(bookList);
for (Book book : bookList) { System.out.println(book); }
break; }
} while (ch != 3); } }

Output:

Practical 7
Write a program for creating a Bank class, which is used to manage
the bank account of customers. Class has two methods, Deposit ()
12202040501019 Dharmik Rabadiya

and withdraw (). Deposit method display old balance and new
balance after depositing the specified amount. Withdrew method
display old balance and new balance after withdrawing. If balance
is not enough to withdraw the money, it throws
ArithmeticException and if balance is less than 500rs after
withdrawing then it throw custom exception,
NotEnoughMoneyException.
Code:
import java.lang.System;
import java.util.*;
class NotEnoughMoneyExecption extends Exception {
public NotEnoughMoneyExecption(String s) {
super(s);
}}
class bankAccount {
double balance, newDeposit, withdraw;
String accountType, name;
Scanner scan = new Scanner(System.in);
public static void exit() {
exit();
}
void createAccount() {
System.out.println("Create New Account");
System.out.print("Enter Your Full Name : ");
name = scan.nextLine();
System.out.print("\nEnter Your Account Type (Saving/Current): ");
accountType = scan.next();
System.out.print("\nEnter Your Initial Balance : ");
balance = scan.nextInt(); }
void deposite() {
System.out.println("Your Current Account Balance is : " + balance);
System.out.print("\nEnter The Amount You Want To Deposite : ");
12202040501019 Dharmik Rabadiya

newDeposit = scan.nextInt();
balance = newDeposit + balance;
System.out.println("Your Account Balance after Depositing " + newDeposit + "Rs. is
"+ balance);
}
void withdraw() {
System.out.println("Money Withdrawl Window");
System.out.println("Your Current Account Balance is : " + balance);
System.out.print("\nEnter The Amount You Want To Withdraw : ");
withdraw = scan.nextInt();
try {
if (balance < withdraw) {
throw new ArithmeticException("Amount Exceede Current Balance");
}
balance = balance - withdraw;
System.out.println("Your Account Balance after Widthrawing " +withdraw +" RS is " +
balance);
try {
if (balance < 500) {
throw new NotEnoughMoneyExecption("Minimum Balance is 500 \nYour Balance is
Below 500");
}
} catch (NotEnoughMoneyExecption e) {
System.out.println(e);
System.exit(0);
} } catch (ArithmeticException e) {
System.out.println(e);
System.exit(0);} }
void display(int ac) {
System.out.println("\nAccount Information");
System.out.println("Name : " + name);
12202040501019 Dharmik Rabadiya

System.out.println("Account Number : " + ac);


System.out.println("Account Type : " + accountType);
System.out.println("Your Account Balance is : " + balance);
}}
class BankMain {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
bankAccount bank[] = new bankAccount[5];
int ch, ac, i = 0;
do {
System.out.println("\nPress 1 to Create Account\nPress 2 to Deposite\nPress 3 for
Widthraw\nPress 4 for Account Information\nPress 5 to exit");
ch = scan.nextInt();
switch (ch) {
case 1:
bank[i] = new bankAccount();
bank[i].createAccount();
i++;
break;
case 2:
System.out.println("Enter Your Account Number : ");
ac = scan.nextInt();
bank[ac].display(ac);
bank[ac].deposite();
break;
case 3:
System.out.println("Enter Your Account Number : ");
ac = scan.nextInt();
bank[ac].display(ac);
bank[ac].withdraw();
break;
12202040501019 Dharmik Rabadiya

case 4:
System.out.println("Enter Your Account Number : ");
ac=scan.nextInt();
bank[ac].display(ac);break;
}
}while(ch!=5);
}}

Output:

2. Write a complete program for calculation average of n +ve


integer numbers of Array A.
a. Read the array form keyboard
b. Raise and handle Exception if
12202040501019 Dharmik Rabadiya

i. Element value is -ve or non-integer.


ii. If n is zero.
Code:
import java.lang.System;
import java.util.*;
class ExceptionClass {
Scanner scan = new Scanner(System.in);
int arr[], n;
ExceptionClass(int n) {
arr = new int[n];
this.n = n;
}
public void readElements() {
System.out.println("Enter elements of array");
for (int i = 0; i < arr.length; i++) {
System.out.printf("Element A[%d] : ", i);
arr[i] = scan.nextInt();
if (arr[i] < 0) {
throw new NegativeArraySizeException("Array Element is Negative");
}}}
public void display() {
System.out.println("Displaying Eements");
for (int i = 0; i < arr.length; i++) {
System.out.printf("Element A[%d] is : %d \n", i, arr[i]);
} }
}
public class ArrayMain {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter The Size of Array : ");
12202040501019 Dharmik Rabadiya

int n = scan.nextInt();
ExceptionClass exception = new ExceptionClass(n);
try {
if (n == 0) {
throw new ArithmeticException("Value of N is Zero");
}
try {
exception.readElements();
exception.display();
} catch (NegativeArraySizeException ne) {
System.out.println(ne);
}
} catch (ArithmeticException ae) {
System.out.println(ae);
}}}

Output:

Practical 8
1. Write a program to find prime numbers in a given range using
both methods of multithreading. Also run the same program using
executor framework.
Code:
12202040501019 Dharmik Rabadiya

import java.io.*;
import java.util.*;
class Thread1 extends Thread {
int max;
public void run() {
Scanner scan = new Scanner(System.in);
System.out.println("Normal By Extending Thread");
System.out.println("Enter Max Range ");
max = scan.nextInt();
int temp = 0;
try {
for (int i = 0; i <= max; i++) {
for (int j = 2; j < i; j++) {
if (i % j == 0) {
temp = 0;
break;
} else {
temp = 1;
}}
if (temp == 1) {
System.out.println(i);
Thread.sleep(1000);
}}
} catch (InterruptedException e) {
System.out.println(e);
}}}
class Thread2 implements Runnable {
@Override
public void run() {
Scanner scan = new Scanner(System.in);
12202040501019 Dharmik Rabadiya

System.out.println("Normal By Implementing Runnable");


System.out.println("Enter Max Range ");
int max = scan.nextInt();
int temp = 0;
try {
for (int i = 0; i <= max; i++) {
for (int j = 2; j < i; j++) {
if (i % j == 0) {
temp = 0;
break;
} else {
temp = 1;
}}
if (temp == 1) {
System.out.println(i);
Thread.sleep(1000);
}}
} catch (InterruptedException e) {
System.out.println(e);
}}}
public class MultithreadingMain {
public static void main(String args[]) {
Thread1 t1 = new Thread1();
t1.start();
Thread2 t2 = new Thread2();
Thread t = new Thread(t2);
t.start();
}}

Output:
12202040501019 Dharmik Rabadiya

2. Assume one class Queue that defines a queue of fixed size says
15.
● Assume one class producer which implements Runnable, having
priority NORM_PRIORITY +1
● One more class consumer implements Runnable, having priority
NORM_PRIORITY-1
● Class TestThread has a main method with maximum priority,
which creates 1 thread for producer and 2 threads for consumer.
● Producer produces a number of elements and puts them on the
queue. when the queue becomes full it notifies other threads.
Consumer consumes a number of elements and notifies other
threads when the queue becomes empty.
Code:
class Item {
int num;
boolean valueSet = false;
public synchronized void put(int num) {
while (valueSet) {
try { wait(); }
catch (Exception e) {}
}
System.out.println("Put : " + num);
this.num = num;
valueSet = true;
12202040501019 Dharmik Rabadiya

notify(); }
public synchronized void get() {
while (!valueSet) {
try {
wait();
} catch (Exception e) {}
}
System.out.println("Get : " + num);
valueSet = false;
notify();
}}
class Producer implements Runnable {
Item item;
public Producer(Item item) {
this.item = item;
Thread produce = new Thread(this, "Producer");
produce.start(); }
public void run() {
int i = 0;
while (true) {
item.put(i++);
try {
Thread.sleep(1000);
} catch (Exception e) {}
}}}
class Consumer implements Runnable {
Item item;
public Consumer(Item item) {
this.item = item;
Thread consume = new Thread(this, "Consumer");
12202040501019 Dharmik Rabadiya

consume.start(); }
public void run() {
while (true) {
item.get();
try {
Thread.sleep(1000);
} catch (Exception e) {}
}}}
class QueueMain {
public static void main(String[] args) {
Item item = new Item();
new Producer(item);
new Consumer(item); } }

Output:

Practical 9
1. Write a program to demonstrate user of ArrayList,
LinkedList ,LinkedHashMap, TreeMap and HashSet Class. And also
12202040501019 Dharmik Rabadiya

implement CRUD operation without database connection using


Collection API.
Code:
import java.io.*;
import java.util.*;
public class Main9 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> arr = new ArrayList<>();
System.out.println("Array List:");
for (int i = 0; i < 5; i++) {
System.out.printf("Enter %d :", i);
arr.add(scan.next());
}
arr.remove(2);
System.out.println("Displaying Array list");
System.out.printf("Value of ArrayList ");
System.out.println(arr);
System.out.println("Linked List");
LinkedList<String> ll = new LinkedList<>();
for (int i = 0; i < 5; i++) {
System.out.printf("Enter %d :", i);
ll.add(scan.next());
}
Iterator<String> itr = ll.iterator();
System.out.println("Displaying Linked list");
System.out.printf("Value of LinkedList ");
while (itr.hasNext()) {
System.out.println(itr.next());
12202040501019 Dharmik Rabadiya

}
System.out.println("LinkedHashMap");
LinkedHashMap<Integer, String> lhm = new LinkedHashMap<>();
for (int i = 0; i < 5; i++) {
System.out.printf("Enter Name %d :", i);
lhm.put(i, scan.next());
}
System.out.println("Displaying Linked list");
System.out.printf("Value of LinkedList ");
for (Map.Entry m : lhm.entrySet()) {
System.out.println(m);
}
System.out.println("TreeMap");
TreeMap<Object, Object> treeMap = new TreeMap<>();
for (int i = 0; i < 5; i++) {
System.out.printf("Enter Name %d :", i);
treeMap.put(i, scan.next());
}
System.out.println("Displaying Linked list");
System.out.printf("Value of Map ");
System.out.println(treeMap);
}
}

Output:
12202040501019 Dharmik Rabadiya

2. Write a program to Sort Array,ArrayList, String, List, Map and Set.


12202040501019 Dharmik Rabadiya

import java.io.*;
import java.util.*;
public class P0902 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> arr = new ArrayList<>();
System.out.println("Array List");
for (int i = 0; i < 5; i++) {
System.out.printf("Enter %d :", i);
arr.add(scan.next());
}
System.out.println("Displaying Array list");
System.out.printf("Value of ArrayList ");
System.out.println(arr);
Collections.sort(arr);
System.out.println("Sorted Array " + arr);
System.out.println("Linked List");
LinkedList<String> ll = new LinkedList<>();
for (int i = 0; i < 5; i++) {
System.out.printf("Enter %d :\n", i);
ll.add(scan.next());
}
Collections.sort(ll);
Iterator<String> itr = ll.iterator();
System.out.println("Displaying Linked list");
System.out.printf("Value of LinkedList\n");
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
12202040501019 Dharmik Rabadiya

Output:

Practical 10
12202040501019 Dharmik Rabadiya

1. Write a program to count occurrences of a given word in a file.


import java.io.*;
import java.util.*;
public class OccurrencesMain
{
public static void main(String[] args) throws IOException{
int count=0;
Scanner scanFromUser = new Scanner(System.in);
FileReader fReader = new FileReader("temp.txt");
Scanner FileData = new Scanner(fReader);
System.out.println("Enter Your Word : ");
String w = scanFromUser.nextLine();
while(FileData.hasNextLine())
{
String str[]=FileData.nextLine().split(" ");
for(int i=0;i<str.length;i++)
{
if(str[i].equals(w)) { count++; }
}
}
FileData.close();
scanFromUser.close();
System.out.printf("The Word '%s' is There %d Times in the Specified File.",w,count);
}}

Output:

2. Write a program to print it self.


12202040501019 Dharmik Rabadiya

Code:
import java.io.*;
import java.util.Scanner;
//Write a program to print it self.
class Readitself{
public static void main(String[] args)
throws IOException,FileNotFoundException {
FileReader fileReader = new FileReader("Readitself.java"); //filename
Scanner scan = new Scanner(fileReader);
while(scan.hasNextLine())
{
System.out.println(scan.nextLine());
}
scan.close();
}
}

Output:

3. Write a program to display list of all the files of given directory.


12202040501019 Dharmik Rabadiya

Code:
import java.io.*;
public class DirectoryMain {
public static void main(String[] args) throws IOException {
File file = new File("D:\12202080501083_shrey");
if (file.isDirectory())
{
System.out.println("Directory Name : " + file.getPath());
String directoryList[] = file.list();
for (int i = 0; i < directoryList.length; i++) {
File list = new File(file.getPath() + "//" + directoryList[i]);
if (list.isDirectory()) {
System.out.println(directoryList[i] + " is Directory.");
} else if (list.isFile()) {
System.out.println(directoryList[i] + " is File.");
}}}}
}

Code:

Practical 11
12202040501019 Dharmik Rabadiya

1. Implement Echo client/server program using TCP.


import java.io.*;
import java.net.*;
class ServerClient {
class Server extends Thread {
static final int PORT_NUMBER = 9999;
static final String IP = "localhost";
void serverConnect() throws Exception {
ServerSocket serverSocket = new ServerSocket(PORT_NUMBER);
System.out.println("Echo Server is Running on PORT : " + PORT_NUMBER);
Socket clientSocket = serverSocket.accept();
Thread.sleep(1000);
System.out.println(
"Client Connected : " + clientSocket.getInetAddress().getHostAddress()
);
Thread.sleep(1000);
InputStream in = clientSocket.getInputStream();
OutputStream out = clientSocket.getOutputStream();
PrintWriter write = new PrintWriter(out, true);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Message From Client : " + line);
}
// out.write("Messege ACK".getBytes());
clientSocket.close();
serverSocket.close();
write.close();
}
public static void main(String[] args) throws Exception {
12202040501019 Dharmik Rabadiya

ServerClient sc = new ServerClient();


Server s = sc.new Server();
s.serverConnect();
}
}
class Client extends Thread {
void clientConnect() throws Exception {
Socket client = new Socket(Server.IP, Server.PORT_NUMBER);
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
// PrintWriter w = new PrintWriter(out,true);
BufferedReader b =new BufferedReader(new InputStreamReader(in));
System.out.print("Sending Messege To Server");
System.out.print(".");
delay();
System.out.print(".");
delay();
System.out.print(".");
delay();
System.out.println(".");
delay();
Thread.sleep(500);
System.out.println("Message Sent");
delay();
out.write("How Are You\n".getBytes());
out.write("What are you doing\n".getBytes());
out.write("Bye Bye!\n".getBytes());
out.flush();
out.close();
client.close();
12202040501019 Dharmik Rabadiya

in.close();
}
public static void main(String[] args) throws Exception {
ServerClient sc = new ServerClient();
Client c = sc.new Client();
c.clientConnect();
}
public static void delay() throws Exception {
Thread.sleep(700);
}}}

Output:
From Client side:

From Server side:

Practical 12
12202040501019 Dharmik Rabadiya

1. Write a program to implement an investment value calculator


using the data inputted by the user. textFields to be included are
amount, year, interest rate and future value. The field “future value”
(shown in gray) must not be altered by the user.
Code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
public class CalculatorMain {
public static void main(String[] args) {
investmentCalculator investmentCalculator = new investmentCalculator(); }}
class investmentCalculator implements ActionListener {
JFrame frame = new JFrame();
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
JTextField amountField = new JTextField();
JTextField yearField = new JTextField();
JTextField intrestRateField = new JTextField();
JTextField futureValueField = new JTextField();
JLabel amountLabel = new JLabel("Amount: ");
JLabel yearLabel = new JLabel("Year: ");
JLabel intrestRateLabel = new JLabel("Intrest Rate: ");
JLabel futureValueLabel = new JLabel("Future Value: ");
investmentCalculator() {
Border border = BorderFactory.createCompoundBorder();
amountLabel.setBounds(70, 50, 75, 25);
12202040501019 Dharmik Rabadiya

yearLabel.setBounds(87, 100, 75, 25);


intrestRateLabel.setBounds(50, 150, 75, 25);
futureValueLabel.setBounds(50, 200, 80, 25);
amountField.setBounds(150, 50, 200, 25);
yearField.setBounds(150, 100, 200, 25);
intrestRateField.setBounds(150, 150, 200, 25);
futureValueField.setBounds(150, 200, 200, 25);
calculateButton.setBounds(155, 300, 100, 25);
calculateButton.addActionListener(this);
calculateButton.setCursor(Cursor.getPredefinedCursor(12));
calculateButton.setBorder(border);
calculateButton.setFocusable(false);
exitButton.setBounds(355, 0, 65, 25);
exitButton.addActionListener(this);
futureValueField.setEditable(false);
futureValueField.setBackground(Color.lightGray);
//-----Label------------
frame.add(amountLabel);
frame.add(yearLabel);
frame.add(futureValueLabel);
frame.add(intrestRateLabel);
frame.getRootPane()
frame.setBorder(BorderFactory.createLineBorder(Color.MAGENTA, 15));
frame.add(calculateButton);
frame.add(exitButton);
frame.add(amountField);
frame.add(yearField);
frame.add(futureValueField);
frame.add(intrestRateField);
frame.setUndecorated(true);
12202040501019 Dharmik Rabadiya

frame.getRootPane().setBorder(BorderFactory.createLineBorder(Color.blue));
frame.setBounds(450, 200, 0, 0);
frame.setBackground(Color.red);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(420, 420);
frame.setLayout(null);
// frame.add(myButton);
frame.setVisible(true); }
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == exitButton) {
frame.dispose(); }
if (e.getSource() == calculateButton) {
String amountFielString = amountField.getText().toString();
String intresstRateString = intrestRateField.getText().toString();
String yearString = yearField.getText().toString();
double amount = Integer.parseInt(String.valueOf(amountFielString));
int year = Integer.parseInt(String.valueOf(yearString));
double intrestRate = Integer.parseInt(String.valueOf(intresstRateString));
double futureValue = (amount * (Math.pow(1 + (intrestRate / 100), year)));
futureValueField.setText(Double.toString(futureValue)); } } }

Output:
12202040501019 Dharmik Rabadiya

2 Write a program which fills the rectangle with the selected color
when the button is pressed.
import java.awt.*;
import java.awt.Color.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.imageio.plugins.tiff.GeoTIFFTagSet;
import javax.swing.*;
class frame extends JFrame implements ActionListener {
JButton red, green, blue;
JPanel PanelRight = new JPanel();
JPanel PanelLeft = new JPanel();
frame() {
PanelLeft.setBounds(0, 0, 200, 200);
PanelLeft.setBackground(Color.green);
PanelLeft.setLayout(null);
PanelRight.setBounds(210, 0, 200, 200);
// PanelRight.setBackground(Color.green);
red = new JButton("Red");
green = new JButton("green");
blue = new JButton("blue");
red.setBounds(20,30,75,25);
blue.setBounds(20,60,75,25);
green.setBounds(20,90,75,25);
blue.setFocusable(true);
setLayout(null);
red.addActionListener(this);
green.addActionListener(this);
blue.addActionListener(this);
12202040501019 Dharmik Rabadiya

add(PanelLeft);
add(PanelRight);
PanelLeft.add(red);
PanelLeft.add(blue);
PanelLeft.add(green);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == red) {
PanelRight.setBackground(Color.red);
} else if (e.getSource() == blue) {
PanelRight.setBackground(Color.blue);
} else if (e.getSource() == green) {
PanelRight.setBackground(Color.green);
}}}
public class ButtonMain {
public static void main(String[] args) {
frame frame = new frame();
frame.setTitle("I Am JFrame");
frame.setSize(410, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}}

Output:

You might also like