河內塔與星號字元之三角形
Download
Report
Transcript 河內塔與星號字元之三角形
河內塔程式:(課本寫法)
/*
public class hanoi
{
static void towerofHanoi(int dishs,int peg1,int peg2,int peg3)
{
if (dishs == 1)
{
System.out.print("盤子從" + peg1);
System.out.println("移到" + peg3);
}
else
{
towerofHanoi(dishs-1, peg1, peg3, peg2);
System.out.print("盤子從" + peg1);
System.out.println("移到" + peg3);
towerofHanoi(dishs-1, peg2, peg1, peg3);
}
}
public static void main(String[] args)
{
int dishs = 3;
towerofHanoi(dishs, 1, 2, 3);
}
}
*/
河內塔程式:(老師寫法)
public class hanoi
{
static int count=0;
public static void main(String[] args)
{
towerofHanoi(3,'A','B','C');
System.out.println("The tatal number of steos is "+count);
}
static void towerofHanoi(int dishes, char from,char by,char to)
{
if (dishes == 1){ //條件終止
System.out.print("盤子從" + from);
System.out.println("移到" + to);
count++;
}
else
{
}
}
}
//第一步驟
towerofHanoi(dishes-1, from, to ,by);
System.out.print("盤子從" + from);
System.out.println("移到" + to);
count++;
//第三步驟
towerofHanoi(dishes-1, by, from, to);
星號字元三角形
public class stars
{
public static void printStars(int i)
{
int x=0;
int y=0;
int z=0;
for(x=0;x<i;x++)
{
for(y=0;y<i;by+)
{
System.out.print(" ");
if(y+1==i-x)
{
for(z=y;z<i;z++)
System.out.print("*");
}
}
System.out.println();
}
}
public static void main(String[] args)
{
printStars(5);
}
}