Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
28 views

Java Programs

Uploaded by

btechbabji08
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Java Programs

Uploaded by

btechbabji08
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

CALCULATOR

import java.awt.*; import java.awt.event.*; import java.applet.*;


/*<applet code="Calculator1" width=300 height=300></applet>*/
public class Calculator1 extends Applet implements ActionListener {
TextField t;
Button b[] = new Button[10];
Button b1[] = new Button[7];
String op2[] = {"+", "-", "*", "/", "%", "=", "C"};
String str1 = "";
int p = 0, q = 0;
String oper;
public void init() {
setLayout(new GridLayout(5, 4));
t = new TextField(20);
setFont(new Font("Arial", Font.BOLD, 20)); int k = 0;
t.setEditable(false);
t.setBackground(Color.pink);
t.setText("0");
for (int i = 0; i < 10; i++) {
b[i] = new Button("" + k);
add(b[i]); k++;
b[i].setBackground(Color.green);
b[i].addActionListener(this); }
for (int i = 0; i < 7; i++) {
b1[i] = new Button("" + op2[i]);
add(b1[i]);
b1[i].setBackground(Color.cyan);
b1[i].addActionListener(this);
} add(t); }
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
if (str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/") || str.equals("%")) {
p = Integer.parseInt(t.getText());
oper = str;
t.setText(str1 = "");
} else if (str.equals("=")) {
str1 = "";
if (oper.equals("+")) {
q = Integer.parseInt(t.getText());
t.setText(String.valueOf((p + q)));
} else if (oper.equals("-")) {
q = Integer.parseInt(t.getText());
t.setText(String.valueOf((p - q)));
} else if (oper.equals("*")) {
q = Integer.parseInt(t.getText());
t.setText(String.valueOf((p * q)));
} else if (oper.equals("/")) {
q = Integer.parseInt(t.getText());
t.setText(String.valueOf((p / q)));
} else if (oper.equals("%")) {
q = Integer.parseInt(t.getText());
t.setText(String.valueOf((p % q)));
}
} else if (str.equals("C")) {
p = 0; q = 0;
t.setText("");
str1 = "";
t.setText("0");
} else {
t.setText(str1.concat(str));
str1 = t.getText();
}}}
a)APPLET
import java.applet.Applet;
import java.awt.*;
/* <applet code="AppletMessage" height="400" width="500"></applet> */
public class AppletMessage extends Applet {
public void paint(Graphics g) {
g.drawString("Hello, welcome to applets", 80, 50);
}
}

b) APPLET(Factorial)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code=FactorialApplet height="400" width="500"></applet>*/
public class FactorialApplet extends JApplet implements ActionListener
{
JPanel p1,p2;
JLabel label1,label2;
JTextField input,result;
JButton compute;
public void init()
{
Container con=getContentPane();
con.setLayout(new BorderLayout());
label1=new JLabel("Enter the number:");
label2=new JLabel("Factorial is:");
input=new JTextField(5);
result=new JTextField(5);
compute=new JButton("Compute");
compute.addActionListener(this);
p1=new JPanel();
p2=new JPanel();
p1.setBackground(Color.red);
p2.setBackground(Color.black);
p1.add(label1);
p1.add(input);
p2.add(label2);
p2.add(result);
p2.add(compute);
con.add(p1,BorderLayout.NORTH);
con.add(p2,BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent ae)
{
int fact=1;
int number=Integer.parseInt(input.getText());
if(ae.getSource()==compute)
{
for(int i=1;i<=number;i++)
{
fact=fact*i;
}
result.setText(String.valueOf(fact));
}
}
}
NUMBER FORMAT
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="NumberFormat.class" height="400" width="400"></applet>*/
public class NumberFormat extends Applet implements ActionListener
{
String msg;
TextField num1, num2, res;
Label l1, l2, l3;
Button div;
public void init()
{
l1= new Label("Number 1");
l2= new Label("Number 2");
l3= new Label("Result");
num1 = new TextField(10);
num2= new TextField(10);
res = new TextField(20);
div = new Button("DIV");
div.addActionListener(this);
add(l1);
add(num1);
add(l2);
add(num2);
add(l3);
add(res);
add(div);
}
public void actionPerformed(ActionEvent ae)
{
String arg=ae.getActionCommand();
if(arg.equals("DIV"))
{
String s1=num1.getText();
String s2 = num2.getText();
int num1= Integer.parseInt(s1);
int num2= Integer.parseInt(s2);
if (num2 == 0)
{
msg="Arithemetic Exception";
repaint();
}
else if ((num1 < 0) || (num2 < 0))
{
msg = "NumberFormat Exception";
repaint();
}
else
{
int num3=num1/num2;
msg = String.valueOf(num3);
}
res.setText(msg);
}
}
public void paint(Graphics g)
{
//g.drawString(msg, 30, 70);
}
}
MULTITHREADING(SQUARE&CUBE)
//MyThread1
import java.util.*;
class MyThread implements Runnable {
int j;
MyThread(int j) {
this.j = j;
}
public void run() {
Random r = new Random();
for (int i = 1; i <= 6; i++) {
j = r.nextInt(10);
if (j % 2 == 0) {
MyThread2 t2 = new MyThread2(j);
t2.start();
} else {
MyThread3 t3 = new MyThread3(j);
t3.start();
}
}
}
}
class MyThread2 extends Thread {
int i;
MyThread2(int a) {
i = a;
}
public void run() {
System.out.println("Square: " + (i * i));
}
}
class MyThread3 extends Thread {
int i;
MyThread3(int b) {
i = b;
}
public void run() {
System.out.println("Cube: " + (i * i * i));
}
}
public class TestThread {
public static void main(String[] args) {
MyThread t1 = new MyThread(0);
Thread p = new Thread(t1);
p.start();
}
}
DLLIST
import java.util.Scanner;
public class Doublell{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
DLList l = new DLList();
int v, ch;
boolean b = true;
while (b) {
System.out.print("1-Insert at beginning\n2-Insert at end\n3-Insert at middle\n4-delete at beginning\n5-
Delete at end\n6-Delete at middle\n7-Display\n8-Exit\nEnter your choice: ");
ch = sc.nextInt();
switch (ch) {
case 1: System.out.print("Enter your data: ");
v = sc.nextInt();
l.inbeg(v);
break;
case 2: System.out.print("Enter your data: ");
v = sc.nextInt();
l.inend(v);
break;
case 3: System.out.print("Enter your data: ");
v = sc.nextInt();
l.inmid(v);
break;
case 4:l.delbeg();
break;
case 5:l.delend();
break;
case 6:l.delmid();
break;
case 7: l.display();
break;
case 8: b=false;
break;
default: System.out.println("Enter a proper choice");
}
}
}
}
class DLList {
Scanner sc=new Scanner(System.in);
static int preval;
Node head;
Node tail;
Node temp;

class Node {
int val;
Node prev;
Node next;
Node(int val) {
this.val=val;
}
}
public void inbeg(int val) {
Node node=new Node(val);
if (head==null) {
head=node;
tail=node;
}
else
{
node.next=head;
head.prev=node;
head=node;
}
}
public void display() {
temp=head;
if(head==null) {
System.out.println("List is empty");
}
else
{
while(temp!=null)
{
System.out.print(temp.val +"<->");
temp=temp.next;
}
System.out.println();
}
}
public void inend(int val) {
Node node=new Node(val);
if(head==null)
{
head=node;
tail=node;
}
else{
temp=head;
while(temp.next!=null)
{
temp=temp.next;
}
temp.next=node;
node.prev=temp;
}
}
public void inmid(int val){
Node node=new Node(val);
int i,loc;
if(head==null){
System.out.println("list is empty");
}
else{
temp=head;
if(head.next==null && head.prev==null)
{
System.out.println("list has only one node");
}
else{
System.out.println("enter the location");
loc = sc.nextInt();
for(i=1;i<loc-1;i++)
{
temp=temp.next;
}
temp.next.prev=node;
node.next=temp.next;
temp.next=node;
node.prev=temp;
}
}
}
public void delbeg()
{
if(head==null)
{
System.out.println("list is empty");
}
else
{
temp=head;
head=head.next;
head.prev=null;
}
}
public void delend(){
if(head==null)
{
System.out.println("list is empty");
}
else
{
temp=head;
if(head.next==null && head.prev==null){
head=null;
}
else
{
while(temp.next!=null)
{
temp=temp.next;
}
temp.prev.next=null;
}
}
}
public void delmid(){
System.out.println("at what value you want to delete");
preval=sc.nextInt();
if(head==null)
{
System.out.println("list is empty");
}
else
{
temp=head;
while(temp!=null){
if(temp.next==null)
{
System.out.println("invalid location");
return;
}
if(temp.val==preval){
temp.next.prev=temp.prev;
temp.prev.next=temp.next;
return;
}
temp=temp.next;
}
System.out.println("Invalid location");
}
}
}
TRAFFIC LIGHTS
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class TrafficLightSimulator extends JFrame implements ItemListener{
public JLabel l1,l2;
public JRadioButton r1,r2,r3;
public ButtonGroup bg;
public JPanel p,p1;
CheckboxGroup ingGrp;
public TrafficLightSimulator(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout());
setSize(800,400);
p=new JPanel(new FlowLayout());
p1=new JPanel(new FlowLayout());
l1=new JLabel();
Font f=new Font("Verdana",Font.BOLD,60);
l1.setFont(f);
add(l1);
p.add(l1);
add(p);
l2=new JLabel("Select Lights: ");
p1.add(l2);
ingGrp=new CheckboxGroup();
Checkbox r1=new Checkbox("RedLight",ingGrp,true);
r1.setBackground(Color.RED);
p1.add(r1);
r1.addItemListener(this);
Checkbox r2=new Checkbox("YellowLight",ingGrp,true);
r2.setBackground(Color.YELLOW);
p1.add(r2);
r2.addItemListener(this);
Checkbox r3=new Checkbox("GreenLight",ingGrp,true);
r3.setBackground(Color.GREEN);
p1.add(r3);
r3.addItemListener(this);
add(p1);
setVisible(true);
}
public void itemStateChanged(ItemEvent i){
Checkbox chk=ingGrp.getSelectedCheckbox();
switch(chk.getLabel()){
case "RedLight":l1.setText("Stop");
l1.setForeground(Color.RED);
break;
case "YellowLight":l1.setText("Ready");
l1.setForeground(Color.YELLOW);
break;
case "GreenLight":l1.setText("Go");
l1.setForeground(Color.GREEN);
break;
}
}
}
public class TrafficLightTest{
public static void main(String[] args){
TrafficLightSimulator a= new TrafficLightSimulator();
}
}
ABSTRACT
abstract class Shape {
int dim1;
int dim2;
Shape(int x, int y) {
dim1 = x;
dim2 = y;
}
abstract void area();
}
class Triangle extends Shape {
Triangle(int x, int y) {
super(x, y);
}
void area() {
System.out.println("Area of Triangle: " + (dim1 * dim2) / 2);
}
}
class Rectangle extends Shape {
Rectangle(int x, int y) {
super(x, y);
}
void area() {
System.out.println("Area of Rectangle: " + (dim1 * dim2));
}
}
class Circle extends Shape {
Circle(int x, int y) {
super(x, y);
}
void area() {
System.out.println("Area of Circle: " + (3.14 * dim1 * dim1));
}
}
class ShapeDemo {
public static void main(String[] args) {
Shape s;
s = new Triangle(60, 30);
s.area();
s = new Rectangle(60, 30);
s.area();
s = new Circle(10, 10);
s.area();
}
}
TABLE(GRID LAYOUT)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.StringTokenizer;
public class Table1 extends JFrame {
int i = 0;
int j = 0, k = 0;
Object data[][] = new Object[5][4];
JButton save;
JTable table1;
FileInputStream fis;
BufferedReader br;
public Table1() {
String d = " ";
Container con = getContentPane();
con.setLayout(new BorderLayout());
final String[] colheads = { "Name", "Roll Number", "Department", "Percentage" };
try {
String s = JOptionPane.showInputDialog("Enter the file name present in the current directory");
FileInputStream fis = new FileInputStream(s);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
while ((d = br.readLine()) != null) {
StringTokenizer st1 = new StringTokenizer(d, ",");
while (st1.hasMoreTokens()) {
for (j = 0; j < 4; j++) {
data[i][j] = st1.nextToken();
System.out.println("data[" + i + "][" + j + "]: " + data[i][j]);
}
i++;
}
System.out.println();
}
} catch (java.lang.Exception e) {
System.out.println("Exception raised: " + e.toString());
}
table1 = new JTable(data, colheads);
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane scroll = new JScrollPane(table1, v, h);
con.add(scroll, BorderLayout.CENTER);
}
public static void main(String[] args) {
{
Table1 t= new Table1();
t.setBackground(Color.green);
t.setTitle("Display Data");
t.setSize (500,300);
t.setVisible(true);
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
}
MOUSE ADAPTER
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter
{
Frame f;
MouseAdapterExample()
{
f=new Frame("MouseAdapter");
f.addMouseListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
Graphics g = f.getGraphics();
g.setColor (Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
g.drawString("mouseClicked",200,100);
}
public static void main(String[] args)
{
new MouseAdapterExample();
}
}
HASH TABLE
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class NameNumberLookup {


public static void main(String[] args) {
Map<String, String> nameNumberMap = new HashMap<>();
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
String[] fields = line.split("\t");
if (fields.length == 2) {
String name = fields[0];
String number = fields[1];
nameNumberMap.put(name, number);
}
}
} catch (IOException e) {
e.printStackTrace();
}
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name or number: ");
String input = scanner.nextLine();
String result = nameNumberMap.get(input);
if (result != null) {
System.out.println("Corresponding value: " + result);
} else {
System.out.println("Entry not found for: " + input);
}
}
}
PRODUCER-CONSUMER
public class Cubbyhole {
private int Contents;
private boolean available = false;

public synchronized int get() {


while (!available) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
available = false;
notifyAll();
return Contents;
}

public synchronized void put(int value) {


while (available) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Contents = value;
available = true;
notifyAll();
}
}
class Producer extends Thread {
private Cubbyhole cubby;
private int number;
public Producer(Cubbyhole c, int number) {
cubby = c;
this.number = number;
}
public void run() {
for (int i = 0; i < 10; i++) {
cubby.put(i);
System.out.println("Produced " + this.number + " put: " + i);
try {
sleep((int) (Math.random() * 100));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer extends Thread {
private Cubbyhole cubby;
private int number;
public Consumer(Cubbyhole c, int number) {
cubby = c;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = cubby.get();
System.out.println("Consumed " + this.number + " got: " + value);
}
}
}
public class ProducerConsumerTest {
public static void main(String[] args) {
Cubbyhole c = new Cubbyhole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
PRINT FILE NAMES
import java.io.File;
import java.io.IOException;

public class CombinedFileDemo {


public static void main(String[] args) {
String directoryPath = "/home/nnrg/528";
File directory = new File(directoryPath);

// Check and create a file


try {
if (directory.createNewFile()) {
System.out.println("New file is created.");
} else {
System.out.println("File already exists.");
}
System.out.println("File path: " + directory.getAbsolutePath());
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}

// List files including those in subdirectories


System.out.println("\nListing all files including subdirectories for: " + directoryPath);
listFilesRecursively(directory);
}

public static void listFilesRecursively(File dir) {


File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
listFilesRecursively(file); // Recursive call for directories
} else {
// Print file details
System.out.println(file.getPath() + "\nLength: " + file.length() + " bytes");
}
}
}
}
}

You might also like