using System; using System.Collections.Generic; using System.Text; //?????使用SOURCE作数组下标时出现 Error 1 The name 'SOURCE' does not exist in the current context C:/Documents and Settings/Manio/My Documents/Visual Studio 2005/Projects/Hanoi/Program.cs 38 54 Hanoi //Hanoi Tower namespace ConsoleApplication1 { class Class2 {
static void Main(string[] args) { int a; Console.WriteLine("Please Input the Number in the Source"); a = Convert.ToInt16( Console.ReadLine() ); Console.WriteLine("Moving Strat!"); Console.WriteLine("=======================================");
//实例化Hanoi Hanoi myHanoi = new Hanoi(a);
//输出信息 Console.WriteLine("======================================="); Console.WriteLine("Moving Ended!"); Console.WriteLine("{0} in Source", a); Console.WriteLine("Moved {0} Time in Total.", myHanoi.time); Console.WriteLine("======================================="); Console.WriteLine(":::::::::::::::::ABOUT:::::::::::::::::"); Console.WriteLine(" This program is written by Manio"); Console.WriteLine(" All Right Reserved!"); Console.WriteLine(" 2006.2.18"); Console.WriteLine(":::::::::::::::::::::::::::::::::::::::"); Console.WriteLine("Press any key to exit this program..."); Console.ReadKey(); } }
public class Hanoi { public const int SOURCE = 1; public const int FREE = 2; public const int TARGET = 3; public int time = 0; int[] HanioTower = new int[4];
public Hanoi(int SourceNumber) { this.HanoiMove(SOURCE, TARGET, SourceNumber); //构造函数中可以调用此类中方法 }
public void HanoiMove(int FromWhere,int ToWhere, int n) { if (n == 1) { this.HanioTower[FromWhere]--; this.HanioTower[ToWhere]++; Console.WriteLine("{0}-->{1}", FromWhere, ToWhere); time++; //在类中引用自身类中定义的变量时,不用this. return; }
for (int i = 1; i <= 3; i++) { if (i != FromWhere && i != ToWhere) { ToWhere = i; break; } }
this.HanoiMove(FromWhere,ToWhere,n-1);
for (int i = 1; i <= 3; i++) { if (i != FromWhere && i != ToWhere) { ToWhere = i; break; } } this.HanoiMove(FromWhere, ToWhere, 1);
for (int i = 1; i <= 3; i++) { if (i != FromWhere && i != ToWhere) { FromWhere = i; break; } } this.HanoiMove(FromWhere, ToWhere, n - 1);