Search This Blog

Showing posts with label program. Show all posts
Showing posts with label program. Show all posts

Java Program for Animated Solution for Tower of Hanoi Puzzle Problem

This is a java program to solve towers of hanoi puzzle problem. This java program give solution for tower of hanoi problem with any number of disks. This program gives animated solution for tower of Hanoi problem. It demonstrates solving the tower of hanoi problem using animation in java.

The solution of hanoi problem given by this program is always optimal. You can enter the number of disks first. This lets you solve puzzle of any level of difficulty. The program is as follows.


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class HanoiAnimated extends JPanel{

static int tower[][];// the three towers' disks as stack
static int top[];//top of the three stacks
static int from,to;//moving 'from' tower number 'to' tower number
static int diskInAir;//number of disk moved (1 to n)
static int n,l,b,u;
static Color colors[]={Color.BLUE,Color.CYAN,Color.GREEN,Color.MAGENTA,Color.ORANGE,Color.PINK,Color.RED,Color.YELLOW};
public HanoiAnimated()
{
    tower=new int[3][10];
    top=new int[3];
}

static void push(int to, int diskno)
//putting disk on tower
{
tower[to-1][++top[to-1]]=diskno;
}

static int pop(int from)
//take topmost disk from tower
{
return(tower[from-1][top[from-1]--]);
}

Color getColor(int disknum)
{
return colors[disknum%8];
}

void drawStill(Graphics g)
{
int j,i,disk;
g.clearRect(0,0,getWidth(),getHeight());
for(j=1;j<=3;j++)
 {
 //draw tower
        g.setColor(Color.GRAY);
 g.fillRoundRect(j*l,u,5,b-u,1,1);
        
 //draw all disks on tower
 for(i=0;i<=top[j-1];i++)
  {
  disk=tower[j-1][i];
                g.setColor(getColor(disk));
  g.fillRect(j*l-15-disk*5,b-(i+1)*10,35+disk*10,10);
  }
 }
}

void drawFrame(Graphics g,int x,int y)
{
try{
drawStill(g);
g.setColor(getColor(diskInAir));
g.fillRect(x-15-diskInAir*5,y-10,35+diskInAir*10,10);
Thread.sleep(60);
}catch(InterruptedException ex){}
}

void animator(Graphics g)
//to show the movement of disk
{
int x,y,dif,sign;
diskInAir=pop(from);
x=from*l;
y=b-(top[from-1]+1)*10;
//taking disk upward from the tower
for(;y>u-20;y-=8)
 drawFrame(g, x, y);

y=u-20;
dif=to*l-x;
sign=dif/Math.abs(dif);
//moving disk towards a target tower
for(;Math.abs(x-to*l)>=24;x+=sign*12)
 drawFrame(g, x, y);
x=to*l;
//placing disk on a target tower
for(;y<b-(top[to-1]+1)*10;y+=8)
 drawFrame(g, x, y);
push(to,diskInAir);
drawStill(g);
}

void moveTopN(Graphics g, int n, int a, int b, int c) throws InterruptedException
//Move top n disk from tower 'a' to tower 'c'
//tower 'b' used for swapping
{
if(n>=1)
 {
 moveTopN(g,n-1,a,c,b);
 drawStill(g);
 Thread.sleep(700);
 from=a;
 to=c;
 //animating the move
 animator(g);
 moveTopN(g,n-1,b,a,c);
 }
}

public static void main(String[] args)
{

int i;
String s=JOptionPane.showInputDialog("Enter number of disks");
n=Integer.parseInt(s);
HanoiAnimated ha=new HanoiAnimated();
//setting all tower empty
for(i=0;i<3;i++)
 top[i]=-1;

//putting all disks on tower 'a'
for(i=n;i>0;i--)
 {
 push(1,i);
 }

JFrame fr=new JFrame();
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setLayout(new BorderLayout());
fr.setSize(640,360);
fr.add(ha);
ha.setSize(fr.getSize());
fr.setVisible(true);
l=ha.getWidth()/4;
b=ha.getHeight()-50;
u=b-n*12;
//start solving
try{
ha.moveTopN(ha.getGraphics(),n,1,2,3);
}catch(Exception ex){}
}

}


Java Program to Display a String in Reverse Order Without Using Loop or Another Array

In this post, we will see a java program to reverse a string without using any loops or temporary array. Such programming questions are often asked in interviews. It is so simple. We make use of recursion to store the string temporarily. Actually, we do not use any loop. We can easily do it without using any loops. Nor we need to declare an extra array. But when we make use of recursion, stack is used internally for calling each instance of the recursive method. Remember, we should not use the reverse method in StringBuilder class or StringBuffer class. The following java program displays the string in reverse order.


import java.util.Scanner;

public class StrRev{
static int len;
static String str;

static void recurse(int i)
{
    if(i<len-1)
        recurse(i+1);
    System.out.print(str.charAt(i));
}

public static void main(String[] arg)
    {
    System.out.println("Enter string");
    Scanner sc = new Scanner(System.in);
    str=sc.nextLine();
    len=str.length();
    recurse(0);
    }
}

In the above java program we just displayed the string in reverse order. we did not reverse the string in memory. In the following java program, we will see how to rearrange the string in reverse order without using any loops or extra arrays.

import java.util.Scanner;

public class StrRev{
static int len;
static char[] str;

static void recurse(int i)
{
    char a=str[i];
    if(i<len-1)
        recurse(i+1);
    str[len-i-1]=a;
}

public static void main(String[] arg)
    {
    System.out.println("Enter string");
    Scanner sc = new Scanner(System.in);
    str=sc.nextLine().toCharArray();
    len=str.length;
    recurse(0);
    System.out.println(String.copyValueOf(str));
    }
}

In the above java program, we stored the input string initially as a character array. Using a recursive method, we rearranged the character array in reverse order. Then we displayed the character array as a string

Java Program to Find Minimum of Two Numbers

Java Program to compare three numbers and display the minimum of two numbers. Here, we will see a simple java program to display the smaller number among two input numbers. This program takes first input as the number of sets of numbers (a set contains two numbers whose minimum is to be displayed). Then it takes numbers as sets of 2 numbers. For every pair of numbers, the java program displays the smaller number. The following java program does it. It makes use of the ternary operator (conditional operator) and Scanner class in java.


import java.util.Scanner;

public class MinofTwo {

public static void main(String[] arg)   
    {
    Scanner sc = new Scanner(System.in);
    int n=sc.nextInt(),a,b;
    while(n>0)
        {
        System.out.println((a=sc.nextInt())<(b=sc.nextInt())?a:b);
        n--;
        }
    }
}

Java Program to Find Minimum of Three

It is the basics of any programming language to compare three numbers and display the minimum of the three. Here, we will see a short java program to display the smallest number among three input numbers. This program takes first input as the number of sets of numbers (a set contains three numbers whose minimum is to be displayed). Then it takes numbers as sets of three numbers. for every three number, the java program displays the smallest of them. The following program does it. It makes use of the ternary operator (conditional operator) and Scanner class.

import java.util.Scanner;

public class MinOfThree {
public static void main(String[] arg)
 
    {
    Scanner sc = new Scanner(System.in);
    int n=sc.nextInt(),a,b,c;
    while(n>0)
        {
        if((a=sc.nextInt())>(b=sc.nextInt()))
            System.out.println(b<(c=sc.nextInt())?b:c);
        else
            System.out.println(a<(c=sc.nextInt())?a:c);
        n--;
        }
    }
}


Body Mass Index Calculator Using Java - Java Application Code

Body Mass Index Calculation is based on your weight and height. Body Mass Index (BMI) = weight/(height*height) where weight is in kilograms and height in meters. The following Java program takes weight and height as input and displays BMI and grades into underweight,Normal, Overweight or obesity.


import java.util.Scanner;

public class BMI {

public static void main(String[] arg)
    {
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter weight in kgs and height in meters");
    float bmi=sc.nextFloat()/(float)Math.pow(sc.nextFloat(),2);
    String s=(bmi<18.5)?"Underweight":(bmi<25)?"Normal weight":(bmi<30)?"Overweight":"Obesity";
    System.out.println("bmi: "+bmi+"   "+s);
    }
}

Calculate your BMI here

Weight (in kg):
Height (in meters):

Java Program to Send a File over a Network after Encryption

Here is a simple java program which can be used to send and receive encrypted files over network. The sender encrypts the file before sending and the receiver decrypts the file and displays it. The program is based on a networking lab experiment at my college. So, although we say 'encryption', characters are simply incremented here. The lab question was as follows:

A client wants a file that is with a server in a secure system. The server encrypts the file in such a way that 'A' will be replaced with 'B', 'B' with 'C'... and 'Z' with 'A' and sends to the client. The client should get file and decrypt it to the original one and display the content. Implement it using TCP/IP.

How to Load a Webpage in a Java App

Do you wonder how to load a webpage in your java application? It is simple. You can load a web document whether it is a web document in internet or a web document from a file in the localhost. I know three methods to do it. You can use JTextPane in java swing (javax.swing), JEditorPane in java swing (javax.swing) or WebView in javaFX (javafx.scene.web.WebView). We will discuss each method to display a webpage in a java application.

The three methods we are going to discuss are:
  • Using JTextPane
  • Using JEditorPane
  • Using WebView in JavaFX

Simple Java Calculator Program Using Java Applet

Java calculator application using java applet JAppet and Swing components. how to make Simple java calculator applet. Java program source code for simple calculator applet
Screenshot of Simple calculator applet in java
This post shows a sample Calculator Program using Java Applet. This program uses the JApplet Class and Swing components in the program. The full source code is given below. This is a java Applet program for a simple calculator with operations addition, subtraction, division and multiplication on floating point numbers. It also have the C (clear) button. This Java Calculator applet was created by myself for my practical lab experiment. I think this may be useful for beginners in java.