Monday, August 3, 2009

Ants





























Free JavaScripts provided

by The JavaScript Source



Clock

import java.applet.*;

import java.awt.*;

import java.util.*;


public class ClockApplet extends Applet implements Runnable{
Thread t,t1;
public void start(){
t = new Thread(this);
t.start();
}

public void run(){
t1 = Thread.currentThread();
while(t1 == t){
repaint();
try{
t1.sleep(1000);
}catch(InterruptedException e){}
}
}

public void paint(Graphics g){
Calendar cal = new GregorianCalendar();
String hour = String.valueOf(cal.get(Calendar.HOUR));
String minute = String.valueOf(cal.get(Calendar.MINUTE));
String second = String.valueOf(cal.get(Calendar.SECOND));
g.drawString(hour + ":" + minute + ":" + second, 20, 30);
}
}

Calculator

/**
This is a simple calculator program can any one take and use.

@author sathish_ssmca
@param nothing */
import javax.swing.*;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
//
public class Calculator extends JApplet {
public void init() {
CalculatorPanel calc=new CalculatorPanel();
getContentPane().add(calc);
}
}

class CalculatorPanel extends JPanel implements ActionListener {
JButton
n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,plus,minus,mul,div,dot,equal;
static JTextField result=new JTextField("0",45);
static String lastCommand=null;
JOptionPane p=new JOptionPane();
double preRes=0,secVal=0,res;

private static void assign(String no)
{
if((result.getText()).equals("0"))
result.setText(no);
else if(lastCommand=="=")
{
result.setText(no);
lastCommand=null;
}
else
result.setText(result.getText()+no);
}

public CalculatorPanel() {
setLayout(new BorderLayout());
result.setEditable(false);
result.setSize(300,200);
add(result,BorderLayout.NORTH);
JPanel panel=new JPanel();
panel.setLayout(new GridLayout(4,4));

n7=new JButton("7");
panel.add(n7);
n7.addActionListener(this);
n8=new JButton("8");
panel.add(n8);
n8.addActionListener(this);
n9=new JButton("9");
panel.add(n9);
n9.addActionListener(this);
div=new JButton("/");
panel.add(div);
div.addActionListener(this);

n4=new JButton("4");
panel.add(n4);
n4.addActionListener(this);
n5=new JButton("5");
panel.add(n5);
n5.addActionListener(this);
n6=new JButton("6");
panel.add(n6);
n6.addActionListener(this);
mul=new JButton("*");
panel.add(mul);
mul.addActionListener(this);

n1=new JButton("1");
panel.add(n1);
n1.addActionListener(this);
n2=new JButton("2");
panel.add(n2);
n2.addActionListener(this);
n3=new JButton("3");
panel.add(n3);
n3.addActionListener(this);
minus=new JButton("-");
panel.add(minus);
minus.addActionListener(this);

dot=new JButton(".");
panel.add(dot);
dot.addActionListener(this);
n0=new JButton("0");
panel.add(n0);
n0.addActionListener(this);
equal=new JButton("=");
panel.add(equal);
equal.addActionListener(this);
plus=new JButton("+");
panel.add(plus);
plus.addActionListener(this);
add(panel,BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==n1) assign("1");
else if(ae.getSource()==n2) assign("2");
else if(ae.getSource()==n3) assign("3");
else if(ae.getSource()==n4) assign("4");
else if(ae.getSource()==n5) assign("5");
else if(ae.getSource()==n6) assign("6");
else if(ae.getSource()==n7) assign("7");
else if(ae.getSource()==n8) assign("8");
else if(ae.getSource()==n9) assign("9");
else if(ae.getSource()==n0) assign("0");
else if(ae.getSource()==dot)
{
if(((result.getText()).indexOf("."))==-1)
result.setText(result.getText()+".");
}
else if(ae.getSource()==minus)
{
preRes=Double.parseDouble(result.getText());
lastCommand="-";
result.setText("0");
}
else if(ae.getSource()==div)
{
preRes=Double.parseDouble(result.getText());
lastCommand="/";
result.setText("0");
}
else if(ae.getSource()==equal)
{
secVal=Double.parseDouble(result.getText());
if(lastCommand.equals("/"))
res=preRes/secVal;
else if(lastCommand.equals("*"))
res=preRes*secVal;
else if(lastCommand.equals("-"))
res=preRes-secVal;
else if(lastCommand.equals("+"))
res=preRes+secVal;
result.setText(" "+res);
lastCommand="=";
}
else if(ae.getSource()==mul)
{
preRes=Double.parseDouble(result.getText());
lastCommand="*";
result.setText("0");
}
else if(ae.getSource()==plus)
{
preRes=Double.parseDouble(result.getText());
lastCommand="+";
result.setText("0");
}

}
}

Thursday, July 30, 2009

Second Synchronized Example

class TwoStrings {
static void print(String str1, String str2) {
System.out.print(str1);
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
}
System.out.println(str2);
}
}

class PrintStringsThread implements Runnable {
Thread thread;
String str1, str2;
TwoStrings ts;
PrintStringsThread(String str1, String str2, TwoStrings ts)
{
this.str1 = str1;
this.str2 = str2;
this.ts = ts;
thread = new Thread(this);
thread.start();
}
public void run() {
synchronized (ts) {
ts.print(str1, str2);
}
}
}

class TestThread {
public static void main(String args[]) {
TwoStrings ts = new TwoStrings();
new PrintStringsThread("Hello ", "there.", ts);
new PrintStringsThread("How are ", "you?", ts);
new PrintStringsThread("Thank you ", "very much!", ts);
}
}

Producer-Consumer Example

The following example is an implementation of the Producer-Consumer problem. A class which provides the methods for generating and consuming an integer value is separated from the Producer and the Consumer thread classes.

class SharedData {
int data;
synchronized void set(int value) {
System.out.println("Generate " + value);
data = value;
}
synchronized int get() {
System.out.println("Get " + data);
return data;
}
}

class Producer implements Runnable {
SharedData sd;
Producer(SharedData sd) {
this.sd = sd;
new Thread(this, "Producer").start();
}
public void run() {
for (int i = 0; i < 10; i++) {
sd.set((int)(Math.random()*100));
}
}
}

class Consumer implements Runnable {
SharedData sd;
Consumer(SharedData sd) {
this.sd = sd;
new Thread(this, "Consumer").start();
}
public void run() {
for (int i = 0; i < 10 ; i++) {
sd.get();
}
}
}

class TestProducerConsumer {
public static void main(String args[]) throws Exception {
SharedData sd = new SharedData();
new Producer(sd);
new Consumer(sd);
}
}

Here is a sample output of the program.

Generate 8
Generate 45
Generate 52
Generate 65
Get 65
Generate 23
Get 23
Generate 49
Get 49
Generate 35
Get 35
Generate 39
Get 39
Generate 85
Get 85
Get 85
Get 85
Generate 35
Get 35
Get 35

This is not what we wanted the program to do. For every value produced by the producer, we expect the consumer to get each value. Here is the output we expect instead.

Generate 76
Get 76
Generate 25
Get 25
Generate 34
Get 34
Generate 84
Get 84
Generate 48
Get 48
Generate 29
Get 29
Generate 26
Get 26
Generate 86
Get 86
Generate 65
Get 65
Generate 38
Get 38
Generate 46
Get 46

To fix the problem with this code, we use the methods for interthread communication.
The following implementation of the Producer-Consumer problem uses the methods for interthread communication.

class SharedData {
int data;
boolean valueSet = false;
synchronized void set(int value) {
if (valueSet) { //has just produced a value
try {
wait();
} catch (InterruptedException ie) {
}
}
System.out.println("Generate " + value);
data = value;
valueSet = true;
notify();
}
synchronized int get() {
if (!valueSet) { //producer hasn't set a value yet
try {
wait();
} catch (InterruptedException ie) {
}
}
System.out.println("Get " + data);
valueSet = false;
notify();
return data;
}
}

/* The remaining part of the code doesn't change. */
class Producer implements Runnable {
SharedData sd;
Producer(SharedData sd) {
this.sd = sd;
new Thread(this, "Producer").start();
}
public void run() {
for (int i = 0; i < 10; i++) {
sd.set((int)(Math.random()*100));
}
}
}

class Consumer implements Runnable {
SharedData sd;
Consumer(SharedData sd) {
this.sd = sd;
new Thread(this, "Consumer").start();
}
public void run() {
for (int i = 0; i < 10 ; i++) {
sd.get();
}
}
}

class TestProducerConsumer {
public static void main(String args[]) throws Exception {
SharedData sd = new SharedData();
new Producer(sd);
new Consumer(sd);
}
}

Interthread Communication

In this section, you'll learn about the basic methods used to allow threads to communicate with other concurrently running threads.

Methods for Interthread Communication

public final void wait()
Causes this thread to wait until some other thread calls the notify or notifyAll method on this object. May throw InterruptedException.

public final void notify()
Wakes up a thread that called the wait method on the same object.

public final void notifyAll()
Wakes up all threads that called the wait method on the same object.

Java Tutorial: Interthread Communication

For a clearer understanding of these methods, let us consider the waiter-customer scenario. In a restaurant scenario, the waiter waits until a customer enters the place instead of continually asking people if they want to order or need anything. When a customer comes in, this signifies the customer's interest in ordering food from the restaurant. In a way, the customer by entering the restaurant notifies the waiter that he is need of his service. However, it is not always the case that the customer is immediately ready with his order. It would be annoying if the waiter continually asks the customer if he's ready with his order every once in a while. Instead, the waiter waits until the customer notifies him that he's ready. Once the customer finished giving his orders, it would be annoying for him to continually nag the waiter if he's order is ready. Normally, a customer would wait until the waiter notifies him and serves the food.

Observe that in this scenario, a party that waits only wakes up once the other party notifies him. The same is true for threads.

The Callable Interface

Recall that there are two ways of creating threads. We can either extend the Thread class or implement the Runnable interface. In whichever technique used, we customize its functionality by overriding the run method. The method has the following signature:


Java Tutorial Source Code: The Callable Interface

public void run()

The drawbacks in creating threads this way are:
  1. The run method cannot return a result since it has void as its return type.
  2. Second, the run method requires you to handle checked exceptions within this method since the overriden method does not use any throws clause.
The Callable interface is basically the same as the Runnable interface without its drawbacks. To get the result from a Runnable task, we have to use some external means of getting the result. A common technique of which is to use an instance variable for storing the result. The next code shows how this can be done.

public MyRunnable implements Runnable {
private int result = 0;

public void run() {
...
result = someValue;
}

/* The result attribute is protected from changes from other
codes accessing this class */
public int getResult() {
return result;
}
}

Java Tutorial Source Code: The Callable Interface

With the Callable interface, getting the result is simple as shown in the next example.

import java.util.concurrent.*;

public class MyCallable implements Callable {
public Integer call() throws java.io.IOException {
...
return someValue;
}
}

The call method has the following signature:

V call throws Exception

V here is a generic type, which means that the return type of call can be of any reference type. You will learn more about generic types in a latter chapter.

There are still more concurrency features in J2SE5.0. Please refer to the API documentation for a detailed discussion of these other features.

Basic Concepts and Notations

In creating a solution in the problem solving process, there is a need for representing higher level data from basic information and structures available at the machine level. There is also a need for synthesis of the algorithms from basic operations available at the machine level to manipulate higher-level representations. These two play an important role in obtaining the desired result. Data structures are needed for data representation while algorithms are needed to operate on data to produce correct output.

In this lesson we will discuss the basic concepts behind the problem-solving process, data types, abstract data types, algorithm and its properties, the addressing methods, useful mathematical functions and complexity of algorithms.

Problem Solving Process

Programming is a problem-solving process, i.e., the problem is identified, the data to manipulate and work on is distinguished and the expected result is determined. It is implemented in a machine known as a computer and the operations provided by the machine is used to solve the given problem. The problem solving process could be viewed in terms of domains – problem, machine and solution.

Problem domain includes the input or the raw data to process, and the output or the processed data. For instance, in sorting a set of numbers, the raw data is set of numbers in the original order and the processed data is the sorted numbers.

The machine domain consists of storage medium and processing unit. The storage medium – bits, bytes, words, etc – consists of serially arranged bits that are addressable as a unit. The processing units allow us to perform basic operations that include arithmetic, comparison and so on.

Solution domain, on the other hand, links the problem and machine domains. It is at the solution domain where structuring of higher level data structures and synthesis of algorithms are of concern.

Data Type, Abstract Data Type and Data Structure

Data type refers to the to the kind of data that variables can assume, hold or take on in a programming language and for which operations are automatically provided. In Java, the primitive data types are:
Keyword    Description

byte Byte-length integer
short Short integer
int Integer
long Long integer
float Single-precision floating point
double Double-precision floating point
char A single character
boolean A boolean value (true or false)
Java Tutorial: Data Type, Abstract Data Type and Data Structure

Abstract Data Type (ADT), on the other hand, is a mathematical model with a collection of operations defined on the model. It specifies the type of data stored. It specifies what its operations do but not how it is done. In Java, ADT can be expressed with an interface, which contains just a list methods. For example, the following is an interface of the ADT stack, which we will cover in detail in Chapter 2:

public interface Stack{
public int size(); /* returns the size of the stack */
public boolean isEmpty(); /* checks if empty */
public Object top() throws StackException;
public Object pop() throws StackException;
public void push(Object item) throws StackException;
}

Java Tutorial: Data Type, Abstract Data Type and Data Structure

Data structure is the implementation of ADT in terms of the data types or other data structures. A data structure is modeled in Java by a class. Classes specify how operations are performed. In Java, to implement an ADT as a data structure, an interface is implemented by a class.

Abstraction and representation help us understand the principles behind large software systems. Information-hiding can be used along with abstraction to partition a large system into smaller subsystems with simple interfaces that makes them easier to understand and use.

Algorithm

Algorithm is a finite set of instructions which, if followed, will accomplish a task. It has five important properties: finiteness, definiteness, input, output and effectiveness. Finiteness means an algorithm must terminate after a finite number of steps. Definiteness is ensured if every step Justify Fullof an algorithm is precisely defined. For example, "divide by a number x" is not sufficient. The number x must be define precisely, say a positive integer. Input is the domain of the algorithm which could be zero or more quantities. Output is the set of one or more resulting quantities which is also called the range of the algorithm. Effectiveness is ensured if all the operations in the algorithm are sufficiently basic that they can, in principle, be done exactly and in finite time by a person using paper and pen.

Java Tutorial Sour Code: Algorithm

Consider the following example:

public class Minimum {

public static void main(String[] args) {
int a[] = { 23, 45, 71, 12, 87, 66, 20, 33, 15, 69 };
int min = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] < min) min = a[i];
}
System.out.println("The minimum value is: " + min);
}
}

Java Tutorial Sour Code: Algorithm

The Java code above returns the minimum value from an array of integers. There is no user input since the data from where to get the minimum is already in the program. That is, for the input and output properties. Each step in the program is precisely defined. Hence, it is definite. The declaration, the for loop and the statement to output will all take a finite time to execute. Thus, the finiteness property is satisfied. And when run, it returns the minimum among the values in the array so it is said to be effective.

Java Tutorial Sour Code: Algorithm

All the properties of an algorithm must be ensured in writing an algorithm.

Addressing Methods

In creating a data structure, it is important to determine how to access the data items. It is determined by the addressing method used. There are two types of addressing methods in general – computed and link addressing methods.

Java Tutorial Sour Code: Addressing Methods: Computed Addressing Method

Computed addressing method is used to access the elements of a structure in pre-allocated space. It is essentially static, an array for example:

int x[] = new int[10];

A data item can be accessed directly by knowing the index on where it is stored.

Link Addressing Method

This addressing method provides the mechanism for manipulating dynamic structures where the size and shape are not known beforehand or if the size and shape changes at runtime. Central to this method is the concept of a node containing at least two fields: INFO and LINK.

Java Tutorial Sour Code: Addressing Methods

In Java,

class Node{
Object info;
Node link;

Node(){
}

Node(Object o, Node l){
info = o;
link = l;
}
}

A Simple AWT Application

You probably have some programs lying around that use regular AWT buttons that you'd love to replace with image buttons, but you don't have the time or, honestly, the necessity to produce your own image button class. Let's look at a simple application that demonstrates an upgrade path you can use on your own programs.

First, let's look at the code for this very simple application:

Java Souce Code:

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

public class ToolbarFrame1 extends Frame {

Button cutButton, copyButton, pasteButton;
public ToolbarFrame1( ) {
super("Toolbar Example (AWT)");
setSize(450, 250);
addWindowListener(new WindowAdapter( ) {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});

ActionListener printListener = new ActionListener( ) {
public void actionPerformed(ActionEvent ae) {
System.out.println(ae.getActionCommand( ));
}
};

Panel toolbar = new Panel( );
toolbar.setLayout(new FlowLayout(FlowLayout.LEFT));

cutButton = new Button("Cut");
cutButton.addActionListener(printListener);
toolbar.add(cutButton);

copyButton = new Button("Copy");
copyButton.addActionListener(printListener);
toolbar.add(copyButton);

pasteButton = new Button("Paste");
pasteButton.addActionListener(printListener);
toolbar.add(pasteButton);

// The "preferred" BorderLayout add call
add(toolbar, BorderLayout.NORTH);
}

public static void main(String args[]) {
ToolbarFrame1 tf1 = new ToolbarFrame1( );
tf1.setVisible(true);
}
}

Saturday, July 18, 2009

String Utility

/*This program Demonstrates the proper use of Number Formats in common java programming scenarios */

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;

/**
* Class provides common functions on number formats.
*/

public class NumberUtility {

/**
* Method takes Object as parameter and returns decimal number.
* if argument is float or double and contains tailing zeros
* it removes them. If argument is float or double then no change in return type.
* Change the Format of the Number by changing the String Pattern
*/
public static String changeToDecimalFormat(Object number) {

BigDecimal bdNumber = new BigDecimal(number.toString());
bdNumber = bdNumber.stripTrailingZeros(); //Returns a BigDecimal with any trailing zero's removed
String pattern = "###,##0.0###########"; //To apply formatting when the number of digits in input equals the pattern
DecimalFormat newFormat = new DecimalFormat(pattern, new DecimalFormatSymbols(Locale.US));
return newFormat.format(bdNumber);

}

/* Method takes Object as parameter and removes commas from the parameter */
public static double removeCommasFromNumber(Object number) {
try {
StringBuffer inputNo = new StringBuffer(number.toString());
if (inputNo.length() > 0) {
while (inputNo.indexOf(",") != -1) {
inputNo.deleteCharAt(inputNo.indexOf(","));
}
} else {
return 0.0;
}
return Double.parseDouble(inputNo.toString());

} catch (NumberFormatException e) {
return 0.0;
}
}

/* Some times its required to have a fixed set of decimal places for a
* number. We can set that by changing the precision number for a particular
* input BigDecimal Input String
*/
public static String changeToRequiredDecimals(String bigDecimalString,
int precision) {
String newFormattedString = null;
String afterDecimal = null;
if (bigDecimalString == null || bigDecimalString.length() == 0) {
return "0.0";
}
if (bigDecimalString.contains(".")) {
afterDecimal = bigDecimalString.substring(bigDecimalString
.indexOf(".") + 1);
int length = Math.abs((afterDecimal.length() - precision));
if (afterDecimal.length() < precision) {
newFormattedString = bigDecimalString;
for (int i = 0; i < length; i++) {
newFormattedString = newFormattedString + "0";
}
} else if (afterDecimal.length() > precision) {
newFormattedString = bigDecimalString.substring(0,
bigDecimalString.length() - length);
if (precision == 0) {
newFormattedString = newFormattedString.substring(0,
newFormattedString.indexOf("."));
} else {
newFormattedString = bigDecimalString;
}

} else {
if (precision > 0)
newFormattedString = bigDecimalString + ".";
else
newFormattedString = bigDecimalString;
for (int i = 0; i < precision; i++) {
newFormattedString = newFormattedString + "0";
}
}
}
return newFormattedString;
}

public static void main(String args[]){
int intVar = 10;
double doubleVar = 10.504000;
float floatVar = 343534534348.5687654F;
String commaString = "343,534,535,000.0";
BigDecimal bdNumber = new BigDecimal("1234.8765");


System.out.println(NumberUtility.changeToDecimalFormat(new Integer(intVar)));
System.out.println(NumberUtility.changeToDecimalFormat(new Double(doubleVar)));
System.out.println(NumberUtility.changeToDecimalFormat(new Float(floatVar)));

System.out.println(NumberUtility.removeCommasFromNumber(commaString));

System.out.println(NumberUtility.changeToRequiredDecimals(bdNumber.toString(), 8));

}
}

Date and Time


/*( This program Demonstrates the proper use of Date functionality in common java programming scenarios*/
)
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtility {

/* Add Day/Month/Year to a Date
add() is used to add values to a Calendar object.
You specify which Calendar field is to be affected by the operation
(Calendar.YEAR, Calendar.MONTH, Calendar.DATE).
*/

public static void addToDate(){
System.out.println("In the ADD Operation");
// String DATE_FORMAT = "yyyy-MM-dd";
String DATE_FORMAT = "dd-MM-yyyy"; //Refer Java DOCS for formats
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
Calendar c1 = Calendar.getInstance();
Date d1 = new Date();
System.out.println("Todays date in Calendar Format : "+c1);
System.out.println("c1.getTime() : "+c1.getTime());
System.out.println("c1.get(Calendar.YEAR): " + c1.get(Calendar.YEAR));
System.out.println("Todays date in Date Format : "+d1);
c1.set(1999,0 ,20); //(year,month,date)
System.out.println("c1.set(1999,0 ,20) : "+c1.getTime());
c1.add(Calendar.DATE,40);
System.out.println("Date + 20 days is : " + sdf.format(c1.getTime()));
System.out.println();
System.out.println();
}


/*Substract Day/Month/Year to a Date
roll() is used to substract values to a Calendar object.
You specify which Calendar field is to be affected by the operation
(Calendar.YEAR, Calendar.MONTH, Calendar.DATE).

Note: To substract, simply use a negative argument.
roll() does the same thing except you specify if you want to roll up (add 1)
or roll down (substract 1) to the specified Calendar field. The operation only
affects the specified field while add() adjusts other Calendar fields.
See the following example, roll() makes january rolls to december in the same
year while add() substract the YEAR field for the correct result

*/


public static void subToDate(){
System.out.println("In the SUB Operation");
String DATE_FORMAT = "dd-MM-yyyy";
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
Calendar c1 = Calendar.getInstance();
c1.set(1999, 0 , 20);
System.out.println("Date is : " + sdf.format(c1.getTime()));

// roll down, substract 1 month
c1.roll(Calendar.MONTH, false);
System.out.println("Date roll down 1 month : " + sdf.format(c1.getTime()));

c1.set(1999, 0 , 20);
System.out.println("Date is : " + sdf.format(c1.getTime()));
c1.add(Calendar.MONTH, -1);
// substract 1 month
System.out.println("Date minus 1 month : " + sdf.format(c1.getTime()));
System.out.println();
System.out.println();
}

public static void daysBetween2Dates(){
Calendar c1 = Calendar.getInstance(); //new GregorianCalendar();
Calendar c2 = Calendar.getInstance(); //new GregorianCalendar();
c1.set(1999, 0 , 20);
c2.set(1999, 0 , 22);
System.out.println("Days Between "+c1.getTime()+"\t"+ c2.getTime()+" is");
System.out.println((c2.getTime().getTime() - c1.getTime().getTime())/(24*3600*1000));
System.out.println();
System.out.println();
}

public static void daysInMonth() {
Calendar c1 = Calendar.getInstance(); //new GregorianCalendar();
c1.set(1999, 6 , 20);
int year = c1.get(Calendar.YEAR);
int month = c1.get(Calendar.MONTH);
// int days = c1.get(Calendar.DATE);
int [] daysInMonths = {31,28,31,30,31,30,31,31,30,31,30,31};
daysInMonths[1] += DateUtility.isLeapYear(year) ? 1 : 0;
System.out.println("Days in "+month+"th month for year "+year+" is "+ daysInMonths[c1.get(Calendar.MONTH)]);
System.out.println();
System.out.println();
}

public static void getDayofTheDate() {
Date d1 = new Date();
String day = null;
DateFormat f = new SimpleDateFormat("EEEE");
try {
day = f.format(d1);
}
catch(Exception e) {
e.printStackTrace();
}
System.out.println("The dat for "+d1+" is "+day);
System.out.println();
System.out.println();
}

public static void validateAGivenDate() {
String dt = "20011223";
String invalidDt = "20031315";
String dateformat = "yyyyMMdd";
Date dt1=null , dt2=null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(dateformat);
sdf.setLenient(false);
dt1 = sdf.parse(dt);
dt2 = sdf.parse(invalidDt);
System.out.println("Date is ok = " + dt1 + "(" + dt + ")");
}
catch (ParseException e) {
System.out.println(e.getMessage());
}
catch (IllegalArgumentException e) {
System.out.println("Invalid date");
}
System.out.println();
System.out.println();
}

public static void compare2Dates(){
SimpleDateFormat fm = new SimpleDateFormat("dd-MM-yyyy");
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();

c1.set(2000, 02, 15);
c2.set(2001, 02, 15);

System.out.print(fm.format(c1.getTime())+" is ");
if(c1.before(c2)){
System.out.println("less than "+c2.getTime());
}else if(c1.after(c2)){
System.out.println("greater than "+c2.getTime());
}else if(c1.equals(c2)){
System.out.println("is equal to "+fm.format(c2.getTime()));
}
System.out.println();
System.out.println();
}

public static boolean isLeapYear(int year){
if((year%100 != 0) || (year%400 == 0)){
return true;
}
return false;
}

public static void main(String args[]){
addToDate();
subToDate();
daysBetween2Dates(); //The "right" way would be to compute the julian day number of both dates and then do the substraction.
daysInMonth();
validateAGivenDate();
compare2Dates();
getDayofTheDate();
}

}

Triangle as follow

/* Display Triangle as follow

1

2 4

3 6 9

4 8 12 16 ... N (indicates no. of Rows) */

class Output3{

public static void main(String args[]){

int n = Integer.parseInt(args[0]);

for(int i=1;i<=n;i++){

for(int j=1;j<=i;j++){

System.out.print((i*j)+" ");

}

System.out.print("\n");

}

}

}

Display Triangle as follow

/* Display Triangle as follow

0

1 0

1 0 1

0 1 0 1 */

class Output2{

public static void main(String args[]){

for(int i=1;i<=4;i++){

for(int j=1;j<=i;j++){

System.out.print(((i+j)%2)+" ");

}

System.out.print("\n");

}

}

}

/* Display Triangle as follow : BREAK DEMO.

1

2 3

4 5 6

7 8 9 10 ... N */

class Output1{

public static void main(String args[]){

int c=0;

int n = Integer.parseInt(args[0]);

loop1: for(int i=1;i<=n;i++){

loop2: for(int j=1;j<=i;j++){

if(c!=n){

c++;

System.out.print(c+" ");

}

else

break loop1;

}

System.out.print("\n");

}

}

}

Display Triangle as follow : BREAK

/* Display Triangle as follow : BREAK DEMO.

1

2 3

4 5 6

7 8 9 10 ... N */

class Output1{

public static void main(String args[]){

int c=0;

int n = Integer.parseInt(args[0]);

loop1: for(int i=1;i<=n;i++){

loop2: for(int j=1;j<=i;j++){

if(c!=n){

c++;

System.out.print(c+" ");

}

else

break loop1;

}

System.out.print("\n");

}

}

}

Display Triangle as follow : BREAK

/* Display Triangle as follow : BREAK DEMO.

1

2 3

4 5 6

7 8 9 10 ... N */

class Output1{

public static void main(String args[]){

int c=0;

int n = Integer.parseInt(args[0]);

loop1: for(int i=1;i<=n;i++){

loop2: for(int j=1;j<=i;j++){

if(c!=n){

c++;

System.out.print(c+" ");

}

else

break loop1;

}

System.out.print("\n");

}

}

}

program for find average of consecutive N Odd no. and Even no

/*Write a program to find average of consecutive N Odd no. and Even no. */

class EvenOdd_Avg{

public static void main(String args[]){

int n = Integer.parseInt(args[0]);

int cntEven=0,cntOdd=0,sumEven=0,sumOdd=0;

while(n > 0){

if(n%2==0){

cntEven++;

sumEven = sumEven + n;

}

else{

cntOdd++;

sumOdd = sumOdd + n;

}

n--;

}

int evenAvg,oddAvg;

evenAvg = sumEven/cntEven;

oddAvg = sumOdd/cntOdd;

System.out.println("Average of first N Even no is "+evenAvg);

System.out.println("Average of first N Odd no is "+oddAvg);

}

}

program for generate Harmonic Series

/* Write a program to generate Harmonic Series.

Example :

Input - 5

Output - 1 + 1/2 + 1/3 + 1/4 + 1/5 = 2.28 (Approximately) */

class HarmonicSeries{

public static void main(String args[]){

int num = Integer.parseInt(args[0]);

double result = 0.0;

while(num > 0){

result = result + (double) 1 / num;

num--;

}

System.out.println("Output of Harmonic Series is "+result);

}

}

switch case program

/* switch case demo

Example :

Input - 124

Output - One Two Four */

class SwitchCaseDemo{

public static void main(String args[]){

try{

int num = Integer.parseInt(args[0]);

int n = num; //used at last time check

int reverse=0,remainder;

while(num > 0){

remainder = num % 10;

reverse = reverse * 10 + remainder;

num = num / 10;

}

String result=""; //contains the actual output

while(reverse > 0){

remainder = reverse % 10;

reverse = reverse / 10;

switch(remainder){

case 0 :

result = result + "Zero ";

break;

case 1 :

result = result + "One ";

break;

case 2 :

result = result + "Two ";

break;

case 3 :

result = result + "Three ";

break;

case 4 :

result = result + "Four ";

break;

case 5 :

result = result + "Five ";

break;

case 6 :

result = result + "Six ";

break;

case 7 :

result = result + "Seven ";

break;

case 8 :

result = result + "Eight ";

break;

case 9 :

result = result + "Nine ";

break;

default:

result="";

}

}

System.out.println(result);

}catch(Exception e){

System.out.println("Invalid Number Format");

}

}

}

program to find whether no. is palindrome or not

/* Write a program to find whether no. is palindrome or not.

Example :

Input - 12521 is a palindrome no.

Input - 12345 is not a palindrome no. */

class Palindrome{

public static void main(String args[]){

int num = Integer.parseInt(args[0]);

int n = num; //used at last time check

int reverse=0,remainder;

while(num > 0){

remainder = num % 10;

reverse = reverse * 10 + remainder;

num = num / 10;

}

if(reverse == n)

System.out.println(n+" is a Palindrome Number");

else

System.out.println(n+" is not a Palindrome Number");

}

}

program to Find whether number is Prime or Not

/* Write a program to Find whether number is Prime or Not. */

class PrimeNo{

public static void main(String args[]){

int num = Integer.parseInt(args[0]);

int flag=0;

for(int i=2;i

if(num%i==0)

{

System.out.println(num+" is not a Prime Number");

flag = 1;

break;

}

}

if(flag==0)

System.out.println(num+" is a Prime Number");

}

}

program to find whether given no. is Armstrong or not.

/*Write a program to find whether given no. is Armstrong or not.

Example :

Input - 153

Output - 1^3 + 5^3 + 3^3 = 153, so it is Armstrong no. */

class Armstrong{

public static void main(String args[]){

int num = Integer.parseInt(args[0]);

int n = num; //use to check at last time

int check=0,remainder;

while(num > 0){

remainder = num % 10;

check = check + (int)Math.pow(remainder,3);

num = num / 10;

}

if(check == n)

System.out.println(n+" is an Armstrong Number");

else

System.out.println(n+" is not a Armstrong Number");

}

}

program for Display Invert Triangle

/* Write a program to Display Invert Triangle.

Example:

Input - 5

Output :

5 5 5 5 5

4 4 4 4

3 3 3

2 2

1

*/

class InvertTriangle{

public static void main(String args[]){

int num = Integer.parseInt(args[0]);

while(num > 0){

for(int j=1;j<=num;j++){

System.out.print(" "+num+" ");

}

System.out.print("\n");

num--;

}

}

}

program for generate a Triangle.

/*Write a program to generate a Triangle.

eg:

1

2 2

3 3 3

4 4 4 4 and so on as per user given number */

class Triangle{

public static void main(String args[]){

int num = Integer.parseInt(args[0]);

for(int i=1;i<=num;i++){

for(int j=1;j<=i;j++){

System.out.print(" "+i+" ");

}

System.out.print("\n");

}

}

}

no. of days into months and days

/* Write a program to convert given no. of days into months and days.

(Assume that each month is of 30 days)

Example :

Input - 69

Output - 69 days = 2 Month and 9 days */

class DayMonthDemo{

public static void main(String args[]){

int num = Integer.parseInt(args[0]);

int days = num%30;

int month = num/30;

System.out.println(num+" days = "+month+" Month and "+days+" days");

}

}

program for Swap the values

/* Write a program to Swap the values */

class Swap{

public static void main(String args[]){

int num1 = Integer.parseInt(args[0]);

int num2 = Integer.parseInt(args[1]);

System.out.println("\n***Before Swapping***");

System.out.println("Number 1 : "+num1);

System.out.println("Number 2 : "+num2);

//Swap logic

num1 = num1 + num2;

num2 = num1 - num2;

num1 = num1 - num2;

System.out.println("\n***After Swapping***");

System.out.println("Number 1 : "+num1);

System.out.println("Number 2 : "+num2);

}

}

Display Multiplication Table

/* Program to Display Multiplication Table */

class MultiplicationTable{

public static void main(String args[]){

int num = Integer.parseInt(args[0]);

System.out.println("*****MULTIPLICATION TABLE*****");

for(int i=1;i<=num;i++){

for(int j=1;j<=num;j++){

System.out.print(" "+i*j+" ");

}

System.out.print("\n");

}

}

}

program to Concatenate string using for Loop

/* Write a program to Concatenate string using for Loop

Example:

Input - 5

Output - 1 2 3 4 5 */

class Join{

public static void main(String args[]){

int num = Integer.parseInt(args[0]);

String result = " ";

for(int i=1;i<=num;i++){

result = result + i + " ";

}

System.out.println(result);

}

}

Friday, July 10, 2009

find integer between 100 and 200

/* Write a program to find sum of all integers greater than 100 and
less than 200 that are divisible by 7 */
class SumOfDigit{
public static void main(String args[]){
int result=0;
for(int i=100;i<=200;i++){
if(i%7==0)
result+=i;
}
System.out.println("Output of Program is : "+result);
}
}

Fibonacci series

/*Write a program to find Fibonacci series of a given no.
Example :
Input - 8
Output - 1 1 2 3 5 8 13 21
*/
class Fibonacci{
public static void main(String args[]){
int num = Integer.parseInt(args[0]); //taking no. as command line argument.
System.out.println("*****Fibonacci Series*****");
int f1, f2=0, f3=1;
for(int i=1;i<=num;i++){
System.out.print(" "+f3+" ");
f1 = f2;
f2 = f3;
f3 = f1 + f2;
}
}
}

Revers the number

class Reverse{
public static void main(String args[]){
int num = Integer.parseInt(args[0]); //take argument as command line
int remainder, result=0;
while(num>0){
remainder = num%10;
result = result * 10 + remainder;
num = num/10;
}
System.out.println("Reverse number is : "+result);
}
}

Revers the number

class Reverse{
public static void main(String args[]){
int num = Integer.parseInt(args[0]); //take argument as command line
int remainder, result=0;
while(num>0){
remainder = num%10;
result = result * 10 + remainder;
num = num/10;
}
System.out.println("Reverse number is : "+result);
}
}

Factorial program

class Sum_Product_ofDigit{
public static void main(String args[]){
int num = Integer.parseInt(args[0]); //taking value as command line argument.
int temp = num,result=0;
//Logic for sum of digit
while(temp>0){
result = result + temp;
temp--;
}
System.out.println("Sum of Digit for "+num+" is : "+result);
//Logic for product of digit
temp = num;
result = 1;
while(temp > 0){
result = result * temp;
temp--;
}
System.out.println("Product of Digit for "+num+" is : "+result);
}
}

To find SUM & PRODUCT OF GIVE DIGIT

class Sum_Product_ofDigit{
public static void main(String args[]){
int num = Integer.parseInt(args[0]); //taking value as command line argument.
int temp = num,result=0;
//Logic for sum of digit
while(temp>0){
result = result + temp;
temp--;
}
System.out.println("Sum of Digit for "+num+" is : "+result);
//Logic for product of digit
temp = num;
result = 1;
while(temp > 0){
result = result * temp;
temp--;
}
System.out.println("Product of Digit for "+num+" is : "+result);
}
}

Switch statement

/* Write a program to display a greet message according to
Marks obtained by student.
*/
class SwitchDemo{
public static void main(String args[]){
int marks = Integer.parseInt(args[0]); //take marks as command line argument.
switch(marks/10){
case 10:
case 9:
case 8:
System.out.println("Excellent");
break;
case 7:
System.out.println("Very Good");
break;
case 6:
System.out.println("Good");
break;
case 5:
System.out.println("Work Hard");
break;
case 4:
System.out.println("Poor");
break;
case 3:
case 2:
case 1:
case 0:
System.out.println("Very Poor");
break;
default:
System.out.println("Invalid value Entered");
}
}
}

Random number

/*Write a program to generate 5 Random nos. between 1 to 100, and it
should not follow with decimal point.
*/
class RandomDemo{
public static void main(String args[]){
for(int i=1;i<=5;i++){
System.out.println((int)(Math.random()*100));
}
}
}

Small Integer not less than the number

/* Write a program that will read a float type value from the keyboard and print the following output.
->Small Integer not less than the number.
->Given Number.
->Largest Integer not greater than the number.
*/
class ValueFormat{
public static void main(String args[]){
double i = 34.32; //given number
System.out.println("Small Integer not greater than the number : "+Math.ceil(i));
System.out.println("Given Number : "+i);
System.out.println("Largest Integer not greater than the number : "+Math.floor(i));
}

Find Minimum of 2 nos. using conditional operator

class Minof2{
public static void main(String args[]){
//taking value as command line argument.
//Converting String format to Integer value
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
int result = (ib

Find Maximum of two Numbers.

class Maxof2{
public static void main(String args[]){
//taking value as command line argument.
//Converting String format to Integer value
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
if(i > j)
System.out.println(i+" is greater than "+j);
else
System.out.println(j+" is greater than "+i);
}
}

chess game

import java.awt.*;
import java.applet.Applet;
import java.net.URL;
import Client;

public class Chess extends Frame
{
String player1;
String player2;
public int move;

public int qizi;

Label msg=new Label("Hello, This is the WeiQi game");

public int[][] bd=new int[20][20];

public int[][] rstct=new int[20][20];

Client cl;

int movedx,movedy;

Button quit=new Button(" Quit the Game ");

Chess(String name1,String name2,int can_move,Client mcl)
{
super(name1+" V.S. "+name2);

player1=name1;
player2=name2;
move=can_move;
qizi=can_move;
cl=mcl;
resize(440,500);

movedx=-1;
movedy=-1;

setLayout(new BorderLayout());

Panel p=new Panel();
p.add(msg);
p.add(quit);

add("North",p);
}

public void oppmove(int y,int x)
{
bd[y][x]=-qizi;
move=1;
movedx=x;
movedy=y;
repaint();
};

public void checkSurround(int qi)
{
int[][] temp=new int[20][20];
for (int i=1;i<=19;i++)
for (int j=1;j<=19;j++)
if (bd[i][j]==0)
temp[i][j]=1;

int counter=999;
while (counter!=0)
{
counter=0;
for (int i=1;i<=19;i++)
for (int j=1;j<=19;j++)
if ((temp[i][j]==1) && (bd[i][j]!=-qi))
{
if ((i>1) && (temp[i-1][j]!=1)) {temp[i-1][j]=1;counter++;};
if ((i<19) && (temp[i+1][j]!=1)) {temp[i+1][j]=1;counter++;};
if ((j>1) && (temp[i][j-1]!=1)) {temp[i][j-1]=1;counter++;};
if ((j<19) && (temp[i][j+1]!=1)) {temp[i][j+1]=1;counter++;};
};
}

for (int i=1;i<=19;i++)
for (int j=1;j<=19;j++)
if ((temp[i][j]==0) && (bd[i][j]==qi))
{
bd[i][j]=0;
rstct[i][j]=1;
};
};

public void paint(Graphics g)
{
if (move==-1)
msg.setText("Waiting for opponent's move...");
else
msg.setText("It is your turn to move !");

for (int i=1;i<=19;i++)
g.drawLine(40,(i+1)*20+40,400,(i+1)*20+40);
for (int j=1;j<=19;j++)
g.drawLine((j+1)*20,80,(j+1)*20,440);

for (int i=1;i<=19;i++)
for (int j=1;j<=19;j++)
if (bd[i][j]==1)
g.fillOval((j+1)*20-10,(i+1)*20+40-10,20,20);
else
if (bd[i][j]==-1)
{
g.setColor(Color.white);
g.fillOval((j+1)*20-10,(i+1)*20+40-10,20,20);
g.setColor(Color.black);
g.drawOval((j+1)*20-10,(i+1)*20+40-10,20,20);
};

if (movedx!=-1)
{
g.setColor(Color.green);
g.drawOval((movedx+1)*20-10,
(movedy+1)*20+40-10,20,20);
g.setColor(Color.black);
};

};

public boolean mouseDown(Event e,int x,int y)
{
if (move==1)
{
x=Math.round((float) x/20)-1;
y=Math.round((float) (y-40)/20)-1;
if ((y>=1) && (y<=19) && (x>=1) && (x<=19)
&& (bd[y][x]==0) && (rstct[y][x]==0))
{
bd[y][x]=qizi;
checkSurround(-qizi);
checkSurround(qizi);
move=-1;
cl.sendRequest("Move "+(y*100+x));
repaint();
}
else
msg.setText("Cannot make that move !");
}
else
msg.setText("Please wait for your opponent ...");
return super.mouseDown(e,x,y);
};

public boolean action(Event e,Object arg)
{
if (e.target==quit)
cl.sendRequest("Endgame");
return super.action(e,arg);
};

};