Tutorials, tips and tricks about java programming language. Answers for many doubts about java programming language. Answering many howtos. Sample java projects and source code, java games, java programs for java practical labs.
Java program can cause a computer to shutdown. In order to shutdown a computer using java code, you should execute the shutdown command in that operating system. The shutdown command is different in Windows and Linux. So, we first check for the operating system. Then we execute appropriate shutdown command.
try {
String command;
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("linux") || os.contains("mac os x"))
command = "shutdown -h now";
else if (os.contains("windows"))
command = "shutdown /p";
else
throw new Exception("Unsupported operating system.");
Runtime.getRuntime().exec(command);
System.exit(0);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
For Linux and Mac OS X, the command for immediate shutdown is shutdown -h now. But in Windows, it is shutdown /p. The above java code checks the operating system. Then it assumes appropriate shutdown command and then executes it. This java code can shutdown a computer.
You can sign out the current user account from windows using java code. Sign out, log out or logoff button can be created using simple lines of code. To logout from Windows operating system using java code, use the following code:
As the above code shows, we are simply executing a cmd command shutdown /l. It is actually running shutdown.exe with parameter /l to force logoff. If you add above code in the actionPerformed() function of a button, the button becomes a logoff button. The following video will show an example in which a simple button is made into a logout button.
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){}
}
}
This is a java program to solve towers of hanoi puzzle problem. This simple java program gives solution for tower of hanoi problem with any number of disks. Tower of Hanoi is a mathematical game or puzzle. It is also called tower of brahma or Lucas' tower. There are three towers (or rods) and a number of disks of different diameters. Initially, The disks have hole at center so that it can slide on to the rods. Initially all disks are stacked on the first tower, say tower A, such that no disk is placed over a smaller disk. The goal or objective is to move all these disks from tower A (first tower) to tower C (third tower). But you should obey the following rules. The rules of towers of hanoi puzzle are:
This is a java program to calculate power of a given number. The inputs are the number and its exponent (power). For example, if you give m and n, the result is m^n. You may use built-in function Math.pow() or hard code it.
Using Built-in Function
import java.util.Scanner;
public class Power{
public static void main(String[] args)
{
int m,n;
Scanner sc=new Scanner(System.in);
System.out.println("Enter number and its power");
m=sc.nextInt();
n=sc.nextInt();
System.out.printf("m^n = %.0f",(float)Math.pow(m,n));
}
}
Without using Built-in function
import java.util.Scanner;
public class Power{
public static void main(String[] args)
{
int m,n,i,p=1;
Scanner sc=new Scanner(System.in);
System.out.println("Enter number and its power");
m=sc.nextInt();
n=sc.nextInt();
for(i=0;i<n;i++)
p*=m;
System.out.printf("m^n = %d",p);
}
}
This is a java program for Matrix Multiplication. To understand how it works, you should first know how matrix multiplication is done mathematically.
import java.util.Scanner;
public class MatrixMult{
public static void main(String[] args)
{
int[][] m1=new int[10][10];
int[][] m2=new int[10][10];
int[][] prod=new int[10][10];
int i,j,k,r1,c1,r2,c2;
Scanner sc=new Scanner(System.in);
System.out.println("Enter number of rows and columns of first matrix:");
r1=sc.nextInt();
c1=sc.nextInt();
System.out.println("Enter number of rows and columns of second matrix:");
r2=sc.nextInt();
c2=sc.nextInt();
if(r2==c1)
{
System.out.println("Enter elements of First matrix (row wise):");
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
m1[i][j]=sc.nextInt();
System.out.println("Matrix1 is :");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
System.out.printf("%d ",m1[i][j]);
System.out.printf("\n");
}
System.out.println("Enter elements of Second matrix (row wise):");
for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
m2[i][j]=sc.nextInt();
System.out.println("Matrix2 is:");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
System.out.printf("%d ",m2[i][j]);
System.out.printf("\n");
}
System.out.println("Product of the Matrices (M1 x M2):");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
prod[i][j]=0;
for(k=0;k<r1;k++)
prod[i][j]+=m1[i][k]*m2[k][j];
System.out.printf("%d ",prod[i][j]);
}
System.out.print("\n");
}
}
else
{
System.out.println("Matrices can't be multiplied.");
System.out.print("No. of columns of first matrix and no of rows of second are different.");
}
}
}
Output
Enter number of rows and columns of first matrix:
2
2
Enter number of rows and columns of second matrix:
2
2
Enter elements of First matrix (row wise):
5
8
6
4
Matrix1 is :
5 8
6 4
Enter elements of Second matrix (row wise):
5
6
8
9
Matrix2 is:
5 6
8 9
Product of the Matrices (M1 x M2):
89 102
62 72
import java.util.Scanner;
public class Multiples{
public static void main(String[] args)
{
int n, i;
Scanner sc=new Scanner(System.in);
System.out.printf("Enter the number:");
n=sc.nextInt();
for(i=1; i<=10; ++i)
System.out.printf("%d * %d = %d \n", i, n, n*i);
}
}
This is a java program to display multiplication tables of all number from 1 to 10. To see java program to display multiplication table of given number only, see this program: Program to Display Multiplication Table of Given Number
public class Multiples{
public static void main(String[] args)
{
int i,j;
for(i=1;i<=10;i++)
{
for(j=1;j<=10;j++)
System.out.printf("%d*%d=%d ",i,j,i*j);
System.out.printf("\n");
}
}
}
This is a java program for rotation transformation in computer graphics. Rotation is one of the important 2d transformations in computer graphics. The program will tell you how to rotate points or polygon around a point (the pivot point). This CG lab program in java language reads the number of sides of polygon, co-ordinates of its vertices, the pivot point for rotation, and angle of rotation. It displays the original polygon and translated polygon in different colors in same screen. This program will tell you how to rotate a polygon in java. I override the paintComponent() method of JPanel to draw on a JPanel.
This program simulates the motion of the components of a two stroke engine. It shows the movement of piston, connecting rod and crank by animating them in java. The program override the paint method of a JFrame to simulate the piston movement in two stroke engine. This can be computer graphics lab (CG lab) problem. The program is as given below. The program uses sin and cos functions to simulate the crank. Also it uses the equation to find the distance between to points.